Spring启动,constructor,@PostConstruct,afterPropertiesSet,onApplicationEvent执行顺序
2016-09-29 11:39
656 查看
package com.xx; import javax.annotation.PostConstruct; import javax.annotation.Resource; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; import com.xx.service.DemoService; @Component public class InitBeanTest implements InitializingBean,ApplicationListener<ContextRefreshedEvent> { @Resource DemoService demoService; public InitBeanTest() { System.err.println("----> InitSequenceBean: constructor: "+demoService); } @PostConstruct public void postConstruct() { System.err.println("----> InitSequenceBean: postConstruct: "+demoService); } @Override public void afterPropertiesSet() throws Exception { System.err.println("----> InitSequenceBean: afterPropertiesSet: "+demoService); } @Override public void onApplicationEvent(ContextRefreshedEvent arg0) { System.err.println("----> InitSequenceBean: onApplicationEvent"); } }
执行结果:
----> 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会被频繁执行,需要使用它监听,需要考虑性能问题。
很显然,这是观察者模式的经典应用。
相关文章推荐
- Spring启动,constructor,@PostConstruct,afterPropertiesSet,onApplicationEvent执行顺序 原创 2016年09月29日 11:39:2
- SpirngMVC系统启动系统配置初始化执行顺序以及防止onApplicationEvent执行两次
- spring @postConstruct init-method constructor和afterSetProperties() 执行顺序
- spring bean中构造函数,afterPropertiesSet和init-method的执行顺序
- 如何在to 4000 mcat启动时,读取数据库到缓存中,onApplicationEvent被执行三次
- 当spring 容器初始化完成后执行某个方法 防止onApplicationEvent方法被执行两次
- spring事件机制-onApplicationEvent执行两次
- 当spring 容器初始化完成后执行某个方法 防止onApplicationEvent方法被执行两次
- 当spring 容器初始化完成后执行某个方法 防止onApplicationEvent方法被执行两次
- Spring InitializingBean的afterPropertiesSet与init-method、@PostConstruct
- Spring,启动程序后顺序执行指定操作
- Working with BeforeProperties and AfterProperties on SPItemEventReceiver
- initMethod 和 afterPropertiesSet 以及 AwareMethod方法的执行时机
- ViewPager的setOnPageChangeListener的三个方法的执行顺序
- Spring AOP @Before @Around @After 等 advice 的执行顺序
- ViewGroup onInterceptTouchEvent,ViewGroup onTouchEvent,View onTouchEvent执行顺序说明
- 用spring的InitializingBean的afterPropertiesSet来初始化
- 用spring的InitializingBean的afterPropertiesSet来初始化
- jedis +springdata spring-data-redis 1.1.1 to 1.2.0 afterPropertiesSet signature exception
- spring的InitializingBean的 afterPropertiesSet 方法 和 init-method配置的 区别联系