一、ConfigurationClassPostProcessor
目的:主要用来处理@Configuration、@PropertySources、@ComponentScans、@ImportResource
- @Configuration:主要用来动态处理一些bean配置
- @PropertySources:处理properties文件定义的bean配置
- @ComponentScans:指定扫描一下bean配置
- @ImportResource:导入由xml指定的bean配置
1.1 关于lite与full的模式说明
对@Configuration区分full模式与lite模式的主要目的在与bean的交叉定义,如:
/**
* 试想,A在这样的定义下默认是个单例,但是如果不特殊处理,在以factory method把B注入容器时,实际上会重新实例化A
* 并且,如果b()方法被外部调用,又会重新实例化B,这显然不符合预期
*/
@Configuration
public class FullMode {
@Bean
public A a() {
return new A();
}
@Bean
public B b() {
return new B(a());
}
public static class A {
}
public static class B {
private A a;
public B(A a) {
this.a = a;
}
}
}
因此,FullMode这个类必须要特殊处理,spring通过cglib处理,大致等价于
@Bean
public A a() {
//当前调用上下文是否在本factory method中,如果是,则new A(),否则从容器中获取A
return new A();
}
这个主要是通过BeanMethodInterceptor实现
public Object intercept(Object enhancedConfigInstance, Method beanMethod, Object[] beanMethodArgs,
MethodProxy cglibMethodProxy) throws Throwable {
.....中间部分沈略
//当前是否在本factory method
//在调用factory method时,spring会把当前的method放入当前线程,可以参见SimpleInstantiationStrategy的instantiate方法
if (isCurrentlyInvokedFactoryMethod(beanMethod)) {
//意味着不是从别的bean创建时依赖了这个bean而创建的
//new A()
return cglibMethodProxy.invokeSuper(enhancedConfigInstance, beanMethodArgs);
}
//从bean factory中拿
return obtainBeanInstanceFromFactory(beanMethod, beanMethodArgs, beanFactory, beanName);
}
lite模式:由@Component、@ComponentScan、@Import、@ImportResource注解的类都是lite,或者存在@Bean的类
二、AutowiredAnnotationBeanPostProcessor
作用:处理@Autowired、@Value、@Inject、@Lookup注入
- @Autowired:标记构造函数、方法、参数、属性需要spring容器注入
- @Value:表达式驱动的依赖注入 占位符${}:静态属性 #{}spel表达式
- @Inject:jsr
- @Lookup:表示一个方法需要被重定向到spring容器的getBean,通过cglib代理重定向,参见
LookupOverrideMethodInterceptor
@Lookup:覆盖原方法,用getBean从容器中获取bean,注意@Lookup只对由容器实例化的bean起作用(需要由cglib代理)
关于注入的重要说明
@Autowired注解的构造函数,按照参数有由多到少进行匹配,并且一个类智能有一个required=true的构造函数
MergedBeanDefinitionPostProcessor:窥视bean的definition,通常会缓存起来(如对prototype的对象特别有效)。
同时依赖注入也会维护bean destroy时的执行顺序
三、RequiredAnnotationBeanPostProcessor
处理@Required
@Required:标记一个方法(通常是setter方法),必须被作为依赖注入
四、CommonAnnotationBeanPostProcessor
处理@PostConstruct、@PreDestroy
@PostConstruct:依赖注入后被调用
@PreDestroy:bean容器销毁时被调用