• @PostConstruct、@Autowired以及构造函数的执行顺序


    结论先行:构造函数 -> PostConstruct -> @Autowired 依次执行

    由于项目需要启动时加载一个配置信息,所以想到了用@PostConstruct,如下所示:

    @Configuration
    public class BUserCenterConfig {
    
        @Value("${b.user.url}")
        public String userCenterUrl;
    
        @Value("${b.user.appId}")
        public String userCenterAppId;
    
        @PostConstruct
        public void setDefaultConfig() {
            UserCenterConfig.SetInterfaceUrl(userCenterUrl);
            UserCenterConfig.SetDefaultAppId(userCenterAppId);
        }
    }

    BeanTest.java

    @Service
    public class BeanTest {
    
        @Autowired
        private BeanTest2 beanTest2;
    
        public BeanTest() {
            System.out.println("this is BeanTest construct. ");
        }
    
        @PostConstruct
        private void init() {
            System.out.println("this is BeanTest init function. ");
            beanTest2.test2();
        }
    }

    BeanTest2.java

    @Service
    public class BeanTest2 {
    
        @PostConstruct
        private void init() {
            System.out.println("this is BeanTest2 init function. ");
        }
    
        public BeanTest2() {
            System.out.println("this is BeanTest2 construct. ");
        }
    
        void test2() {
            System.out.println("this is BeanTest2 test2 function. ");
        }
    }

    启动项目,输出结果如下:

    this is BeanTest construct. 
    this is BeanTest2 construct. 
    this is BeanTest2 init function. 
    this is BeanTest init function. 
    this is BeanTest2 test2 function. 

  • 相关阅读:
    素因子分解
    【转载】一张表看懂LTE和5G NR的区别
    看国家宝藏,顺便学习一下国密算法
    LTE-Advanced(4G)主要技术学习:CA、CoMp、HetNet
    未来移动通信的需求与挑战
    傅里叶级数
    正余弦函数的复指数表示
    网络基础——相关面试考点
    操作系统——相关面试考点
    小米2015笔试编程题
  • 原文地址:https://www.cnblogs.com/miaoying/p/11761199.html
Copyright © 2020-2023  润新知