public class ServiceBean<T> extends ServiceConfig<T> implements InitializingBean, DisposableBean, ApplicationContextAware, ApplicationListener<ContextRefreshedEvent>, BeanNameAware { private static final long serialVersionUID = 213195494150089726L; private static transient ApplicationContext SPRING_CONTEXT; private final transient Service service; private transient ApplicationContext applicationContext; private transient String beanName; private transient boolean supportedApplicationListener;
spring 容器中通过@PostConstruct和@PreDestroy可以对Bean进行初始化和销毁;或者通InitializingBean和DisposableBean实现对Bean的初始化和销毁。
这说明在spring初始化bean的时候,如果bean实现了InitializingBean接口,会自动调用afterPropertiesSet方法。
public void afterPropertiesSet() throws Exception { if (getProvider() == null) {
进行了以上各种Model,Config的初始化。
核心方法为:onApplicationEvent,监听所有发送到ApplicationContext中到Event。
public synchronized void export() { if (provider != null) { if (export == null) { export = provider.getExport();
} if (delay == null) {
delay = provider.getDelay();
}
} if (export != null && !export) { return;
} if (delay != null && delay > 0) {
delayExportExecutor.schedule(new Runnable() { public void run() {
doExport();
}
}, delay, TimeUnit.MILLISECONDS);
} else {
doExport();
}
}
通过一个延迟线程池,对各种Config,Model进行初始化。
通过ApplicationContext可以获取Spring容器中的所有Bean,也可以通过setApplicationContext获取Spring上下文。
public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext;
SpringExtensionFactory.addApplicationContext(applicationContext); if (applicationContext != null) {
SPRING_CONTEXT = applicationContext; try {
Method method = applicationContext.getClass().getMethod("addApplicationListener", new Class<?>[]{ApplicationListener.class}); // backward compatibility to spring 2.0.1
method.invoke(applicationContext, new Object[]{this});
supportedApplicationListener = true;
} catch (Throwable t) { if (applicationContext instanceof AbstractApplicationContext) { try {
Method method = AbstractApplicationContext.class.getDeclaredMethod("addListener", new Class<?>[]{ApplicationListener.class}); // backward compatibility to spring 2.0.1
if (!method.isAccessible()) {
method.setAccessible(true);
}
method.invoke(applicationContext, new Object[]{this});
supportedApplicationListener = true;
} catch (Throwable t2) {
}
}
}
}
}