zoukankan      html  css  js  c++  java
  • 哪个先执行:@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

  • 相关阅读:
    不懂就问」CPU 到底是怎么识别代码的?
    StackOverflow经典问题:代码中如何去掉烦人的“!=null"判空语句
    在 Excel 中使用正则表达式进行查找与替换
    从浅入深详解独立ip网站域名恶意解析的解决方案
    CentOS配置防火墙操作实例
    三步解决fiddler升级后https无法通过证书验证问题
    apache http跳转到https代码
    openssl命令行将pfx格式转.key和.crt文件,Apache适用
    宝塔面板常用命令大全!
    CentOS如何挂载硬盘
  • 原文地址:https://www.cnblogs.com/softidea/p/10230828.html
Copyright © 2011-2022 走看看