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

2023-03-07 14:33:10 浏览数 (1)

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

0 人点赞