Spring 源码(十)Spring Aware自动装配原理

Spring Aware自动装配有两种实现方式:

  1. 在初始化Bean的initializeBean方法中执行invokeAwareMethods方法
  2. 通后置处理器ApplicationContextAwareProcessor来实现的,它实现了BeanPostProcessor接口

invokeAwareMethods

我们在初始化Bean的时候,为了保证一部分Aware必须在后置处理器postProcessBeforeInitialization方法之前执行,所以在Bean初始化之前直接调用了invokeAwareMethods方法。源码如下:

private void invokeAwareMethods(final String beanName, final Object bean) {
    if (bean instanceof Aware) {
        if (bean instanceof BeanNameAware) {
            ((BeanNameAware) bean).setBeanName(beanName);
        }
        if (bean instanceof BeanClassLoaderAware) {
            ((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
        }
        if (bean instanceof BeanFactoryAware) {
            ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
        }
    }
}

ApplicationContextAwareProcessor

除了上诉涉及的Aware,剩余部分的Aware的自动装配都是在ApplicationContextAwareProcessor#postProcessBeforeInitialization中实现的,该方法最终会去调用invokeAwareInterfaces方法。源码如下:

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);
        }
    }
}

总结

从上面源码我们可以看出,不管是哪种实现方式,我们执行过程都是一样的:

  1. 判断是否实现了Aware接口
  2. 判断具体实现了那个Aware接口
  3. 直接调用XxxAware接口的特有方法实现XxxAware的自动装配

推荐阅读更多精彩内容