spring中实现自己的初始化逻辑

实现这两个listener都可以进行自己的初始化逻辑。
InitializingBean.afterPropertiesSet 这个优先调用
ApplicationListener.onApplicationEvent 这个后调用

他们分别由 AbstractApplicationContext.refresh 方法
调用的如下两个函数调用到的:
finishBeanFactoryInitialization(beanFactory);
finishRefresh();

public class InitListener implements ApplicationListener, InitializingBean {

@Resource
private AboutDao aboutDao;

@Override
public void afterPropertiesSet() throws Exception {
System.out.println("afterPropertiesSet");


Integer count = 0;
try {
count = aboutDao.count();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(count);


}

@Override
public void onApplicationEvent(ApplicationEvent event) {

//防止重复调用
ApplicationContext ctx = (ApplicationContext) event.getSource();
if (ctx.getParent() != null) {
return;
}


System.out.println("onApplicationEvent");
Integer count = 0;
try {
count = aboutDao.count();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(count);

}
}
posted @ 2018-01-05 14:33  范世强  阅读(345)  评论(0编辑  收藏  举报