哪个先执行:@PostConstruct和@Bean的initMethod?

结论:

/**
* step1:执行构造函数
* step2:执行使用@PostConstruct注解修饰的方法【如果有多个,则执行顺序不确定】
* step3:执行@Bean注解中initMethod指定的方法
*/

 

示例代码:
@Slf4j
public class InitBean {

    public InitBean() {
        log.info("Step1:begin to execute Constructor Function");
    }

    public void initMethod() {
        log.info("Step3:begin to execute initMethod");
    }


    @PostConstruct
    public void postConstructMethod1() {
        log.info("Step2:begin to execute  postConstructMethod1 with @PostConstruct");
    }

    @PostConstruct
    public void postConstructMethod2() {
        log.info("Step2:begin to execute postConstructMethod2 with @PostConstruct");
    }

}

 

Java Config方式进行Bean的初始化:

@Configuration
public class InitBeanConfig {

    @Bean(initMethod = "initMethod")
    public InitBean initBean() {
        return new InitBean();
    }

}

 

测试用例:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = InitBeanConfig.class)
public class InitBeanConfigTest {

    @Test
    public void givenBean_WhenInit_thenFirstConstructorFunction_SecondPostConstructAnna_ThirdInitMethod() {
        /**
         * step1:执行构造函数
         * step2:执行使用@PostConstruct注解修饰的方法
         * step3:执行@Bean注解中initMethod指定的方法
         */
    }

}

 

执行结果:
2019-01-06 22:16:03.362 INFO 21944 --- [main] c.t.learning.init.spring.InitBean : Step1:begin to execute Constructor Function
2019-01-06 22:16:03.377 INFO 21944 --- [main] c.t.learning.init.spring.InitBean : Step2:begin to execute postConstructMethod1 with @PostConstruct
2019-01-06 22:16:03.378 INFO 21944 --- [main] c.t.learning.init.spring.InitBean : Step2:begin to execute postConstructMethod2 with @PostConstruct
2019-01-06 22:16:03.378 INFO 21944 --- [main] c.t.learning.init.spring.InitBean : Step3:begin to execute initMethod
2019-01-06 22:16:03.461 INFO 21944 --- [main] c.t.l.init.spring.InitBeanConfigTest: Started InitBeanConfigTest in 3.548 seconds (JVM running for 5.781)

 

温馨提示: 如果存在多个使用注解@PostConstruct修饰的方法,则这些方法执行顺序不确定

 

代码:
https://github.com/helloworldtang/spring-boot-cookbook/blob/v1.0.2-thymeleaf/learning-demo/src/main/java/com/tangcheng/learning/init/spring/InitBean.java

转载于:https://www.cnblogs.com/softidea/p/10230828.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值