springBoot启动时让方法自动执行的几种实现方式

本文介绍了在Spring框架中可以通过多种方式定义在应用启动过程中执行特定任务的方法,包括实现ServletContextAware接口、ServletContextListener接口、ApplicationRunner接口及CommandLineRunner接口等。

1.实现ServletContextAware接口并重写其setServletContext方法

@Component
public class TestStarted implements ServletContextAware {
    /**
     * 在填充普通bean属性之后但在初始化之前调用
     * 类似于initializingbean的afterpropertiesset或自定义init方法的回调
     *
     */
    @Override
    public void setServletContext(ServletContext servletContext) {
        System.out.println("setServletContext方法");
    }
}

注意:该方法会在填充完普通Bean的属性,但是还没有进行Bean的初始化之前执行

2.实现ServletContextListener接口

/**
     * 在初始化Web应用程序中的任何过滤器或servlet之前,将通知所有servletContextListener上下文初始化。
     */
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        //ServletContext servletContext = sce.getServletContext();
        System.out.println("执行contextInitialized方法");
    }

3.将要执行的方法所在的类交个spring容器扫描(@Component),并且在要执行的方法上添加@PostConstruct注解或者静态代码块执行

@Component
public class Test2 {
    //静态代码块会在依赖注入后自动执行,并优先执行
    static{
        System.out.println("---static--");
    }
    /**
     *  @Postcontruct’在依赖注入完成后自动调用
     */
    @PostConstruct
    public static void haha(){
        System.out.println("@Postcontruct’在依赖注入完成后自动调用");
    }
}

4.实现ApplicationRunner接口

/**
     * 用于指示bean包含在SpringApplication中时应运行的接口。可以定义多个applicationrunner bean
     * 在同一应用程序上下文中,可以使用有序接口或@order注释对其进行排序。
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("ApplicationRunner的run方法");
    }

5.实现CommandLineRunner接口

/**
     * 用于指示bean包含在SpringApplication中时应运行的接口。可以在同一应用程序上下文中定义多个commandlinerunner bean,并且可以使用有序接口或@order注释对其进行排序。
     * 如果需要访问applicationArguments而不是原始字符串数组,请考虑使用applicationrunner。
     * 
     */
    @Override
    public void run(String... ) throws Exception {
        System.out.println("CommandLineRunner的run方法");
    }
### Spring Boot 启动类的多种编写方法 Spring Boot 的启动类通常通过 `@SpringBootApplication` 注解来定义,该注解是一个复合注解,包含了以下几个核心功能: - **`@SpringBootConfiguration`**: 表明这是一个配置类。 - **`@EnableAutoConfiguration`**: 开启自动配置机制[^2]。 - **`@ComponentScan`**: 执行组件扫描,默认会扫描当前包及其子包下的所有带有特定注解(如 `@Controller`, `@Service`, `@Repository` 等)的类。 以下是几种常见的 Spring Boot 启动类编写方式: #### 1. 使用默认的 `@SpringBootApplication` 这是最常见的实现方式。只需在一个主类上加上 `@SpringBootApplication` 注解并提供一个 `main` 方法即可完成应用的初始化和运行。 ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } ``` 这种方式适用于大多数场景,并能充分利用 Spring Boot 提供的自动化配置能力。 --- #### 2. 自定义扫描路径 如果项目结构复杂或者需要指定某些特定包进行扫描,则可以通过自定义 `@ComponentScan` 来调整扫描范围。 ```java import org.springframework.boot.SpringApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan(basePackages = {"com.example.service", "com.example.repository"}) public class CustomScanApplication { public static void main(String[] args) { SpringApplication.run(CustomScanApplication.class, args); } } ``` 此方法允许开发者更灵活地控制哪些模块被加载到上下文中[^1]。 --- #### 3. 不使用 `@SpringBootApplication` 而单独声明各部分 对于一些特殊需求的应用程序,可以不依赖于 `@SpringBootApplication` 组合注解,而是分别显式添加所需的各个组成部分。 ```java import org.springframework.boot.SpringApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @Configuration @EnableAutoConfiguration @ComponentScan(basePackages = "com.example") public class ModularizedApplication { public static void main(String[] args) { SpringApplication.run(ModularizedApplication.class, args); } } ``` 这种方法适合那些希望更加精细管理应用程序生命周期以及减少潜在冲突的情况。 --- #### 4. 配置外部化参数支持 有时可能需要根据环境变量或其他动态条件决定如何启动服务,在这种情况下可以在启动过程中传入额外参数。 ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ParameterizedApplication { public static void main(String[] args) { System.setProperty("spring.profiles.active", "dev"); // 设置激活 profile SpringApplication app = new SpringApplication(ParameterizedApplication.class); app.setDefaultProperties(Collections.singletonMap("custom.property", "value")); app.run(args); } } ``` 上述例子展示了如何设置活动 Profile 和其他默认属性值。 --- #### 5. 嵌套 Web 应用程序入口点 当构建的是基于 Servlet 容器的传统 Java EE 或者微服务架构中的 RESTful API 接口时,还可以进一步扩展以适应不同的部署模式。 ```java import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; public class ServletContainerApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(ServletContainerApplication.class); } public static void main(String[] args) { new SpringApplicationBuilder(ServletContainerApplication.class).run(args); } } ``` 这段代码片段说明了怎样让 Spring Boot 支持 WAR 文件形式打包以便兼容传统服务器容器的需求。 --- ### 总结 以上列举了几种不同类型的 Spring Boot 启动类设计思路,每一种都有其适用场合。实际开发中应依据具体业务逻辑和技术栈特点选择最合适的方案。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值