Spring启动时实现初始化的几种方式

准确的说是spring容器实例化完成后,几种初始化的方式。为什么这么说呢?下看面示例:

@Slf4j
@Component
public class InitBeanDemo {
    @Autowired
    private Environment env;

    public InitBeanDemo() {
        log.info("DefaultProfiles: {}", Arrays.asList(env.getDefaultProfiles()));
        log.info("ActiveProfiles: {}", Arrays.asList(env.getActiveProfiles()));
    }

示例是在bean的构造方法里做一些初始化的工作,示例比较简单只做了日志打印。是理想很丰满,现实很骨感,报错了:Constructor threw exception; nested exception is java.lang.NullPointerException。
原因是,Environment尚未初始化完成。


接下来我们来探索一下 有哪些初始化方式能满足上面示例的需求。


构造方法里初始化

可以正常运行,在所有初始化方式里执行时机最早。原理是在InitBeanDemo实例化前就实例化了Environment。

@Component
public class InitBeanDemo {

    private final Environment env;

    @Autowired
    public InitBeanDemo (Environment environment) {
        this.env = environment;
        log.info("Constructor DefaultProfiles: {}", Arrays.asList(env.getDefaultProfiles()));
        log.info("Constructor ActiveProfiles: {}", Arrays.asList(env.getActiveProfiles()));
    }
}

常规三件套

常规三件套:@PostConstruct、InitializingBean、initMethod。 如果你愿意的话,三种方式可以在同一个Bean下同时使用,执行的优先级@PostConstruct > InitializingBean > initMethod。

@PostConstruct注解

在一个可以被扫描到Bean里,添加一个public void xxx()方法并加上@PostConstruct注解,方法里编写需要初始化的逻辑。
同一个应用程序里可以有多个@PostConstruct注解,同一个Bean里也可以有多个@PostConstruct注解。

@Slf4j
@Component
public class InitBeanDemo {
    @Autowired
    private Environment env;

    @PostConstruct
    public void init() {
        log.info("@PostConstruct DefaultProfiles: {}", Arrays.asList(env.getDefaultProfiles()));
        log.info("@PostConstruct ActiveProfiles: {}", Arrays.asList(env.getActiveProfiles()));
    }

实现InitializingBean接口

实现InitializingBean接口,在afterPropertiesSet() 方法里编写需要初始化的逻辑。
同一个应用程序里可以有多个实现InitializingBean接口的类,执行时机会按类名的自然顺序排序。

@Slf4j
@Component
public class InitBeanDemo implements InitializingBean {
    @Autowired
    private Environment env;

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("InitializingBean DefaultProfiles: {}", Arrays.asList(env.getDefaultProfiles()));
        log.info("InitializingBean ActiveProfiles: {}", Arrays.asList(env.getActiveProfiles()));
    }
}

指定Bean的initMethod方法

使用@Bean注解的initMethod属性可用于Bean的初始化后执行的方法。initMethod必须是public void 的无参构造方法。

@Slf4j
public class InitBeanDemo implements InitializingBean {
    @Autowired
    private Environment env;
    
	public void initMethod() {
        log.info("initMethod DefaultProfiles: {}", Arrays.asList(env.getDefaultProfiles()));
        log.info("initMethod ActiveProfiles: {}", Arrays.asList(env.getActiveProfiles()));
    }
@Configuration
public class InitBeanConfig {

    @Bean(initMethod="initMethod")
    public InitBeanDemo initBeanDemo () {
        return new InitBeanDemo();
    }

}

等同于 在XML 配置中的init-method属性:

<bean id="initBeanDemo" class="com.xxx.InitBeanDemo" init-method="initMethod"></bean>

自定义ApplicationListener监听

两种方式,一种实现接口,另一种使用注解。

实现ApplicationListener接口

监听ContextRefreshedEvent事件。

@Slf4j
@Component
public class InitBeanDemo implements ApplicationListener<ContextRefreshedEvent>{
    @Autowired
    private Environment env;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        log.info("ApplicationListener DefaultProfiles: {}", Arrays.asList(env.getDefaultProfiles()));
        log.info("ApplicationListener ActiveProfiles: {}", Arrays.asList(env.getActiveProfiles()));
    }
}

@EventListener注释

方法参数里指定ContextRefreshedEvent事件。

@Slf4j
@Component
public class InitBeanDemo {
    @Autowired
    private Environment env;

    @EventListener
    public void onApplicationEvent2(ContextRefreshedEvent event) {
        log.info("@EventListener DefaultProfiles: {}", Arrays.asList(env.getDefaultProfiles()));
        log.info("@EventListener ActiveProfiles: {}", Arrays.asList(env.getActiveProfiles()));
    }
}

Spring Boot提供的初始化接口

ApplicationRunner接口

@Slf4j
@Component
public class InitBeanDemo implements ApplicationRunner {
    @Autowired
    private Environment env;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("ApplicationRunner: {}", args);
        log.info("ApplicationRunner: {}", args.getOptionNames());
        log.info("ApplicationRunner DefaultProfiles: {}", Arrays.asList(env.getDefaultProfiles()));
        log.info("ApplicationRunner ActiveProfiles: {}", Arrays.asList(env.getActiveProfiles()));
    }
}

CommandLineRunner接口

可以在同一个应用程序上下文中定义多个CommandLineRunner bean,并且可以使用@Ordered接口或@Order注释进行排序。

@Slf4j
@Component
public class InitBeanDemo implements CommandLineRunner {
    @Autowired
    private Environment env;

    @Override
    public void run(String... args) throws Exception {
        log.info("CommandLineRunner: {}", args);
        log.info("CommandLineRunner DefaultProfiles: {}", Arrays.asList(env.getDefaultProfiles()));
        log.info("CommandLineRunner ActiveProfiles: {}", Arrays.asList(env.getActiveProfiles()));
    }
}

在同一个Bean里使用以上初始化方式的执行先后顺序

在同一个Bean里使用以上初始化方式,运行的日志片段:

2021-06-07 11:24:41|INFO |main|c.c.s.s.t.ConstructorInitDemo|Constructor DefaultProfiles: [default]
2021-06-07 11:24:41|INFO |main|c.c.s.s.t.ConstructorInitDemo|Constructor ActiveProfiles: [sit]

2021-06-07 11:24:42|INFO |main|c.c.s.s.test.InitBeanDemo|@PostConstruct DefaultProfiles: [default]
2021-06-07 11:24:42|INFO |main|c.c.s.s.test.InitBeanDemo|@PostConstruct ActiveProfiles: [sit]
2021-06-07 11:24:42|INFO |main|c.c.s.s.test.InitBeanDemo|InitializingBean DefaultProfiles: [default]
2021-06-07 11:24:42|INFO |main|c.c.s.s.test.InitBeanDemo|InitializingBean ActiveProfiles: [sit]
2021-06-07 11:24:42|INFO |main|c.c.s.s.test.InitBeanDemo|initMethod DefaultProfiles: [default]
2021-06-07 11:24:42|INFO |main|c.c.s.s.test.InitBeanDemo|initMethod ActiveProfiles: [sit]

2021-06-07 11:24:44|INFO |main|c.c.s.s.test.InitBeanDemo|@EventListener DefaultProfiles: [default]
2021-06-07 11:24:44|INFO |main|c.c.s.s.test.InitBeanDemo|@EventListener ActiveProfiles: [sit]
2021-06-07 11:24:44|INFO |main|c.c.s.s.test.InitBeanDemo|ApplicationListener DefaultProfiles: [default]
2021-06-07 11:24:44|INFO |main|c.c.s.s.test.InitBeanDemo|ApplicationListener ActiveProfiles: [sit]


2021-06-07 11:24:44|INFO |main|c.c.s.s.test.InitBeanDemo|ApplicationRunner: org.springframework.boot.DefaultApplicationArguments@68bef3df
2021-06-07 11:24:44|INFO |main|c.c.s.s.test.InitBeanDemo|ApplicationRunner: []
2021-06-07 11:24:44|INFO |main|c.c.s.s.test.InitBeanDemo|ApplicationRunner DefaultProfiles: [default]
2021-06-07 11:24:44|INFO |main|c.c.s.s.test.InitBeanDemo|ApplicationRunner ActiveProfiles: [sit]

2021-06-07 11:24:44|INFO |main|c.c.s.s.test.InitBeanDemo|CommandLineRunner: {}
2021-06-07 11:24:44|INFO |main|c.c.s.s.test.InitBeanDemo|CommandLineRunner DefaultProfiles: [default]
2021-06-07 11:24:44|INFO |main|c.c.s.s.test.InitBeanDemo|CommandLineRunner ActiveProfiles: [sit]

也即 整篇文章整理的先后顺序。



Spring Boot中实现应用启动时初始化操作有多种方法,以下是几种常见的方式: 1. **使用`CommandLineRunner`或`ApplicationRunner`接口**: 这两个接口都提供了在Spring Boot应用启动后执行代码的机制。`CommandLineRunner`的`run`方法接收一个`String`数组作为参数,而`ApplicationRunner`的`run`方法接收一个`ApplicationArguments`对象。 ```java import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; @Component public class MyCommandLineRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { // 初始化操作 System.out.println("CommandLineRunner: 初始化操作"); } } ``` ```java import org.springframework.boot.ApplicationRunner; import org.springframework.boot.ApplicationArguments; import org.springframework.stereotype.Component; @Component public class MyApplicationRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { // 初始化操作 System.out.println("ApplicationRunner: 初始化操作"); } } ``` 2. **使用`@PostConstruct`注解**: `@PostConstruct`注解用于在依赖注入完成后执行初始化方法。这个方法会在`CommandLineRunner`和`ApplicationRunner`之前执行。 ```java import javax.annotation.PostConstruct; import org.springframework.stereotype.Component; @Component public class MyPostConstructBean { @PostConstruct public void init() { // 初始化操作 System.out.println("@PostConstruct: 初始化操作"); } } ``` 3. **实现`InitializingBean`接口**: `InitializingBean`接口提供了一个`afterPropertiesSet`方法,该方法在所有属性设置完成后被调用。 ```java import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Component; @Component public class MyInitializingBean implements InitializingBean { @Override public void afterPropertiesSet() throws Exception { // 初始化操作 System.out.println("InitializingBean: 初始化操作"); } } ``` 4. **使用`ApplicationListener`**: 通过实现`ApplicationListener`接口,可以监听特定的应用程序事件,例如`ContextRefreshedEvent`,在事件触发时执行初始化操作。 ```java import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; @Component public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { // 初始化操作 System.out.println("ApplicationListener: 初始化操作"); } } ``` 这些方法各有优缺点,选择哪种方式取决于具体的应用场景和需求。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值