哪个先执行:@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