谈谈Spring的ApplicationContextAware接口
现象:
我们写一个类,实现ApplicationContextAware接口,类上再加一个@Component后,运行项目,你会发现在我们实现的setApplicationContext会传进来Spring的ApplicationContext。
@Component
public class TestMyBeanPostProcess implements ApplicationContextAware {
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
/* 此处将会传进来ApplicationContext */
}
}
为什么?
对于应用方面,我们只需要知道实现此接口再@Component即可,但我相信你还是比较喜欢知道Spring具体怎么做的。
源码查看
首先:
// 创建AnnotationConfigApplicationContext,传入AppConfig.class配置类
new AnnotationConfigApplicationContext(AppConfig.class);
// AppConfig.class中代码如下:
@Configuration
@ComponentScan("com.dh")
public class AppConfig {
}
进入到AnnotationConfigApplicationContext的构造函数中:
/**
* Create a new AnnotationConfigApplicationContext, deriving bean definitions
* from the given annotated classes and automatically refreshing the context.
* @param annotatedClasses one or more annotated classes,
* e.g. {@link Configuration @Configuration} classes
*/
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
this();
register(annotatedClasses);
refresh();
}
// 这里面第一行代码this():
public AnnotationConfigApplicationContext() {
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
// 这里干的事情我们忽略不计,就是设置一个reader和scanner,分别对应这两个类:AnnotatedBeanDefinitionReader reader;ClassPathBeanDefinitionScanner scanner;这两个类做的什么事情也不要去多想,这不是这次的重点(涉及到Spring的Bean信息扫描和读取)。
// 再看下一行register(annotatedClasses);
// 这里面实际上做的事情就是将我们传入的AppConfig.class解析信息,包括带的注解等其他信息,然后封装到BeanDefinition中然后存入到beanNameList和BeanDefinitionList中。
重要的第三行“refresh()”调用的方法:
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.,准备提前工作
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.,获取BeanFactory
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.本次的重点代码
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
prepareBeanFactory()为重点的代码:
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
// 设置classLoader以及其他一些对象
beanFactory.setBeanClassLoader(getClassLoader());
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
//
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
// BeanFactory interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// Register early post-processor for detecting inner beans as ApplicationListeners.
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found.
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// Register default environment beans.
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
}
// 注意看这一行:beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)):
从这一行代码很简单,但不简单的是ApplicationContextAwareProcessor和BeanPostProcessor。
BeanPostProcessor:
是一个可以让我们干预Bean实例化的接口,当我们实现此接口并重写里面的postProcessBeforeInitialization、postProcessAfterInitialization方法的后,每个Bean实例化完成后都会调用这两个方法,那么当有多个类实现了BeanPostProcessor的时候,如果想指定BeanPostProcessor被调用的顺序的话,需要实现此接口:PriorityOrdered,此接口的返回值越小执行的顺序越靠前。BeanPostProcessor此扩展接口可以使我们干预Bean的实例化过程,例如实现AOP等功能,例如我们注入一个A类,里面有一个a方法,然后我们实现BeanPostProcessor接口的类当中postProcessBeforeInitialization方法里面会传入这个实例化后的A类,我们在这方法里面使用任意动态代理方法来对其进行代理,再将代理后得到的类return回去,此时Spring容器中的A类就是我们返回的已经代理过后的类,这样就实现了AOP的操作,当然其他的大部分功能都可以使用BeanPostProcessor来进行实现,Spring默认提供了50个以上的BeanPostProcessor,其中包含参数校验、aop的功能。总结一下:BeanPostProcessor是Spring给我们提供的扩展接口,此扩展接口可以让我们干预Bean的实例化过程已达到某些功能,当然扩展点肯定不止BeanPostProcessor一个,还有大约4个左右,例如BeanFactoryPostProcessor等。
ApplicationContextAwareProcessor:
/**
* 此PostProcessor中包含很多回调方法,例如拿到Application,拿到Environment,然后通过接口的方法设置回去
*/
class ApplicationContextAwareProcessor implements BeanPostProcessor {
private final ConfigurableApplicationContext applicationContext;
private final StringValueResolver embeddedValueResolver;
/**
* Create a new ApplicationContextAwareProcessor for the given context.
*/
public ApplicationContextAwareProcessor(ConfigurableApplicationContext applicationContext) {
this.applicationContext = applicationContext;
this.embeddedValueResolver = new EmbeddedValueResolver(applicationContext.getBeanFactory());
}
@Override
@Nullable
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
AccessControlContext acc = null;
/* 在这里判断当前的bean是否实现我们需要操作的接口,如果有的话,那么设置acc */
if (System.getSecurityManager() != null &&
(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {
acc = this.applicationContext.getBeanFactory().getAccessControlContext();
}
if (acc != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareInterfaces(bean);
return null;
}, acc);
}
else {
/* 如果acc不为空,则去挨个判断实现的接口,然后去其进行回调 */
invokeAwareInterfaces(bean);
}
return bean;
}
private void invokeAwareInterfaces(Object bean) {
if (bean instanceof Aware) {
if (bean instanceof EnvironmentAware) {
((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
}
if (bean instanceof EmbeddedValueResolverAware) {
((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
}
if (bean instanceof ResourceLoaderAware) {
((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
}
if (bean instanceof ApplicationEventPublisherAware) {
((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
}
if (bean instanceof MessageSourceAware) {
((MessageSourceAware) bean).setMessageSource(this.applicationContext);
}
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
}
}
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
return bean;
}
}
进入到这个类里面来以后会发现,它实现了BeanPostProcessor接口,并重写了我们上面提到的两个方法:postProcessBeforeInitialization,postProcessAfterInitialization。重点看postProcessBeforeInitialization,在这里面先是一堆判断,这些判断我们不关心,看invokeAwareInterfaces(bean),这一行方法调用。
在这个方法里面判断当前类是否实现了EnvironmentAware接口,如果实现了则强转后将Environmentset过去,后续if中都是相同的道理,只是接口不同,此时我们就能发现最后里面就是我们文章标题里面写的ApplicationContextAware接口,那么看到这里你是不是有点明白了。对,就是你想的那样。