0
点赞
收藏
分享

微信扫一扫

Spring启动,constructor,@PostConstruct,afterPropertiesSet,onApplicationEvent执行顺序

生活记录馆 2022-03-30 阅读 47


  1. package com.xx;
  2. import javax.annotation.PostConstruct;
  3. import javax.annotation.Resource;
  4. import org.springframework.beans.factory.InitializingBean;
  5. import org.springframework.context.ApplicationListener;
  6. import org.springframework.context.event.ContextRefreshedEvent;
  7. import org.springframework.stereotype.Component;
  8. import com.xx.service.DemoService;
  9. @Component
  10. public class InitBeanTest implements InitializingBean,ApplicationListener<ContextRefreshedEvent> {
  11. @Resource
  12. DemoService demoService;
  13. public InitBeanTest() {
  14. System.err.println("----> InitSequenceBean: constructor: "+demoService);
  15. }
  16. @PostConstruct
  17. public void postConstruct() {
  18. System.err.println("----> InitSequenceBean: postConstruct: "+demoService);
  19. }
  20. @Override
  21. public void afterPropertiesSet() throws Exception {
  22. System.err.println("----> InitSequenceBean: afterPropertiesSet: "+demoService);
  23. }
  24. @Override
  25. public void onApplicationEvent(ContextRefreshedEvent arg0) {
  26. System.err.println("----> InitSequenceBean: onApplicationEvent");
  27. }
  28. }



执行结果:

----> InitSequenceBean: constructor: null

----> InitSequenceBean: postConstruct: com.yiniu.kdp.service.impl.DemoServiceImpl@40fe544

----> InitSequenceBean: afterPropertiesSet: com.yiniu.kdp.service.impl.DemoServiceImpl@40fe544

----> InitSequenceBean: onApplicationEvent

----> InitSequenceBean: onApplicationEvent

分析:

构造函数是每个类最先执行的,这个时候,bean属性还没有被注入

postConstruct优先于afterPropertiesSet执行,这时属性竟然也被注入了,有点意外

spring很多组建的初始化都放在afterPropertiesSet做。我们在做一些中间件想和spring一起启动,可以放在这里启动。

onApplicationEvent属于应用层的时间,最后被执行,很容易理解。注意,它出现了两次,为什么?因为bean注入了DemoService,spring容器会被刷新。

换言之onApplicationEvent会被频繁执行,需要使用它监听,需要考虑性能问题。

很显然,这是观察者模式的经典应用。


梅花香自古寒来


举报

相关推荐

0 条评论