前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >哪个先执行:@Bean的initMethod or @PostConstruct

哪个先执行:@Bean的initMethod or @PostConstruct

作者头像
烟雨平生
发布2023-03-07 14:33:10
1810
发布2023-03-07 14:33:10
举报
文章被收录于专栏:数字化之路数字化之路
from heiyanquan
结论:
代码语言:javascript
复制
/**
 * step1:执行构造函数
 * step2:执行使用@PostConstruct注解修饰的方法
 * step3:执行@Bean注解中initMethod参数指定的方法
 */
Talk is cheap,show me the code... 上码:
定义的示例Bean:
代码语言:javascript
复制
@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的初始化:

代码语言:javascript
复制
@Configuration
public class InitBeanConfig {

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

}
测试用例:
代码语言:javascript
复制
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = InitBeanConfig.class)
public class InitBeanConfigTest {

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

}
执行结果:
代码语言:javascript
复制
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

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-01-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 的数字化之路 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 结论:
  • Talk is cheap,show me the code... 上码:
  • 定义的示例Bean:
  • 测试用例:
  • 执行结果:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档