1、Spring中使用applicationContext对象
public class SpringContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) { applicationContext = applicationContext; } public static ApplicationContext getApplicationContext() { return applicationContext; } }
2、为什么继承ApplicationContextAware就可以使用applicationContext对象?
使用后置处理器
3、什么是后置处理器?
后置处理器主要是对bean进行增强,包括在bean初始化前和初始化后进行增强,如修改bean属性、对bean的方法进行代理等。
public interface BeanPostProcessor { // bean初始化前增强 default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } // bean初始化后增强 default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; }
4、后置处理器怎样调用setApplicationContext赋值?
内置后置处理器:org.springframework.context.support.ApplicationContextAwareProcessor
class ApplicationContextAwareProcessor implements BeanPostProcessor public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException { else { invokeAwareInterfaces(bean); } return bean; } private void invokeAwareInterfaces(Object bean) { if (bean instanceof Aware) { // 对继承于ApplicationContextAware的bean调用setApplicationContext方法进行赋值 if (bean instanceof ApplicationContextAware) { ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext); } } }
5、参考资料