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

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

执行结果:

----> 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会被频繁执行,需要使用它监听,需要考虑性能问题。

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

原文地址:https://www.cnblogs.com/zhuyeshen/p/11788338.html