Springboot2.x—— InitializingBean项目初始化执行

1、实现InitializingBean接口,重写afterPropertiesSet()在bean初始化时会执行该方法

@Configuration
public class RecoveryManagerJob implements InitializingBean {

    /**
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {

        System.out.println("————————————————————————————i am after properties set");

    }
}

2、添加其他注解 运行时 查看 跟afterPropertiesSet()的实现顺序

新建接口:

public interface Car {

    public String carName();
}

新建class 实现该接口

@Service
public class BMW implements  Car{


    @Override
    public String carName() {
        return "bmw";
    }
}

在 RecoveryManagerJob类中添加 以下内容 ,查看执行顺序

@Configuration
public class RecoveryManagerJob implements InitializingBean {


    /**
     * //Constructor -> @Autowired -> @PostConstruct -> afterPropertiesSet() -> init-method
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {

        System.out.println("————————————————————————————i am after properties set");

    }

    @Autowired
    private Car car;

    // 先生成对象RecoveryManagerJob1 再 注入Car
    public RecoveryManagerJob() {
        System.out.println("————————————————————————————此时car未被注入,打印car会空指针" );
    }

    @PostConstruct
    public void start(){
        System.out.println("————————————————————————————i am postconstrruct, i will revcovery the jobs..."+ car.carName());
    }


    // 最后执行
    @Bean
    public void init() throws Exception {

        System.out.println("————————————————————————————i am init-method");

    }
}

执行结果如下:可以看到具体 顺序://Constructor(构造器) -> @Autowired -> @PostConstruct -> afterPropertiesSet() -> init-method

2020-10-10 17:41:11.051  INFO 2505 --- [  restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1510 ms
————————————————————————————此时car未被注入,打印car会空指针
————————————————————————————i am postconstrruct, i will revcovery the jobs...bmw
————————————————————————————i am after properties set
————————————————————————————i am init-method
2020-10-10 17:41:11.272  INFO 2505 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-10-10 17:41:11.824  INFO 2505 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2020-10-10 17:41:11.860  INFO 2505 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8082 (http) with context path ''
2020-10-10 17:41:11.870  INFO 2505 --- [  restartedMain] com.wx.web.RemindApplication             : Started RemindApplication in 2.687 seconds (JVM running for 3.324)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值