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

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

由于项目需要启动时加载一个配置信息,所以想到了用@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. 
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值