1.AnnotationConfigApplicationContext详细分析
1.1 概述
使用AnnotationConfigApplicationContext可以实现基于Java的配置类(包括各种注解)加载Spring的应用上下文。避免使用application.xml进行配置。相比XML配置,更加便捷。
* Standalone application context, accepting annotated classes as input - in particular
* {@link Configuration @Configuration}-annotated classes, but also plain
* {@link org.springframework.stereotype.Component @Component} types and JSR-330 compliant
* classes using {@code javax.inject} annotations. Allows for registering classes one by
* one using {@link #register(Class...)} as well as for classpath scanning using
* {@link #scan(String...)}.
*
* <p>In case of multiple {@code @Configuration} classes, @{@link Bean} methods defined in
* later classes will override those defined in earlier classes. This can be leveraged to
* deliberately override certain bean definitions via an extra {@code @Configuration}
* class.
1.2 类结构层次分析
主要类或接口说明:
GenericApplicationContext——通用应用上下文,内部持有一个DefaultListableBeanFactory实例,这个类实现了BeanDefinitionRegistry接口,可以在它身上使用任意的bean definition读取器。典型的使用案例是:通过BeanFactoryRegistry接口注册bean definitions,然后调用refresh()方法来初始化那些带有应用上下文语义(org.springframework.context.ApplicationContextAware)的bean,自动探测org.springframework.beans.factory.config.BeanFactoryPostProcessor等。
BeanDefinitionRegistry——用于持有像RootBeanDefinition和 ChildBeanDefinition实例的bean definitions的注册表接口。DefaultListableBeanFactory实现了这个接口,因此可以通过相应的方法向beanFactory里面注册bean。GenericApplicationContext内置一个DefaultListableBeanFactory实例,它对这个接口的实现实际上是通过调用这个实例的相应方法实现的。
AbstractApplicationContext——ApplicationContext接口的抽象实现,没有强制规定配置的存储类型,仅仅实现了通用的上下文功能。这个实现用到了模板方法设计模式,需要具体的子类来实现其抽象方法。自动通过registerBeanPostProcessors()方法注册BeanFactoryPostProcessor, BeanPostProcessor和ApplicationListener的实例用来探测bean factory里的特殊bean——对比1分析
AnnotationConfigRegistry——注解配置注册表。用于注解配置应用上下文的通用接口,拥有一个注册配置类和扫描配置类的方法。
1.2 构造函数
- AnnotatedBeanDefinitionReader——BeanDefinition解析器用来解析带注解的bean
- ClassPathBeanDefinitionScanner——bean的扫描器 用来扫描类
- 注册解析传入的配置类(使用类配置的方式进行解析)
- 调用容器的refresh方法初始化容器
/**
* Create a new AnnotationConfigApplicationContext that needs to be populated
* through {@link #register} calls and then manually {@linkplain #refresh refreshed}.
*/
public AnnotationConfigApplicationContext() {
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
/**
* Create a new AnnotationConfigApplicationContext with the given DefaultListableBeanFactory.
* @param beanFactory the DefaultListableBeanFactory instance to use for this context
*/
public AnnotationConfigApplicationContext(DefaultListableBeanFactory beanFactory) {
super(beanFactory);
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
/**
* 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();
}
/**
* Create a new AnnotationConfigApplicationContext, scanning for bean definitions
* in the given packages and automatically refreshing the context.
* @param basePackages the packages to check for annotated classes
*/
public AnnotationConfigApplicationContext(String... basePackages) {
this();
scan(basePackages);
refresh();
}
1.3 AnnotatedBeanDefinitionReader的构造器
- 注解的条件判断器ConditionEvaluator
该方法在初始化的时调用,当配置的类上有@Conditional注解并且返回false的时候,容器就不处理该类 - AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry)
这个是关键,注册AnnotationConfigProcessor
/**
* Create a new {@code AnnotatedBeanDefinitionReader} for the given registry.
* If the registry is {@link EnvironmentCapable}, e.g. is an {@code ApplicationContext},
* the {@link Environment} will be inherited, otherwise a new
* {@link StandardEnvironment} will be created and used.
* @param registry the {@code BeanFactory} to load bean definitions into,
* in the form of a {@code BeanDefinitionRegistry}
* @see #AnnotatedBeanDefinitionReader(BeanDefinitionRegistry, Environment)
* @see #setEnvironment(Environment)
*/
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
this(registry, getOrCreateEnvironment(registry));
}
/**
* Create a new {@code AnnotatedBeanDefinitionReader} for the given registry and using
* the given {@link Environment}.
* @param registry the {@code BeanFactory} to load bean definitions into,
* in the form of a {@code BeanDefinitionRegistry}
* @param environment the {@code Environment} to use when evaluating bean definition
* profiles.
* @since 3.1
*/
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
Assert.notNull(environment, "Environment must not be null");
this.registry = registry;
this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
2.注解分析的关键方法loadBeanDefinitionsForBeanMethod
该方法具体实现对包括如下注解的处理。
- autowire
- initMethod
- destroyMethod
Conditional配置类Ch5MainConfig.java
@Configuration
public class Ch5MainConfig {
@Bean("person")
public Person person(){
System.out.println("给容器中添加person.......");
return new Person("person",20);
}
@Conditional(WinCondition.class)
@Bean("lison")
public Person lison(){
System.out.println("给容器中添加lison.......");
return new Person("Lison",58);
}
@Conditional(LinCondition.class)
@Bean("james")//bean在容器中的ID为james, IOC容器MAP, map.put("id",value)
public Person james(){
System.out.println("给容器中添加james.......");
return new Person("james",20);
}
}
2.1 Ch5MainConfig注册
是在 register(annotatedClasses)阶段。
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
this();
register(annotatedClasses);
refresh();
}
调用栈:
2.2 @Bean的分析
是在refresh的invokeBeanFactoryPostProcessors(beanFactory)阶段,核心方法是loadBeanDefinitionsForBeanMethod,该方法处理了各种各样的注解。
-
调用栈
2.3 @Conditional(LinCondition.class)分析
ConditionEvaluator:配置的类上有@Conditional注解并且返回false的时候,容器就不处理该类。
-
调用到LinCondition时实际的栈信息
3.@Autowired
重点关注AutowiredAnnotationBeanPostProcessor后置处理器。
* @author Juergen Hoeller
* @author Mark Fisher
* @since 2.5
* @see AutowiredAnnotationBeanPostProcessor
* @see Qualifier
* @see Value
*/
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
/**
* Declares whether the annotated dependency is required.
* <p>Defaults to {@code true}.
*/
boolean required() default true;
}
3.1 当AutowiredAnnotationBeanPostProcessor 作为接口MergedBeanDefinitionPostProcessor的实现时
- AutowiredAnnotationBeanPostProcessor后置处理器的方法调用栈postProcessMergedBeanDefinition
该方法是在AbstractAutowireCapableBeanFactory.java的doCreateBean中调用的。该方法是创建bean实例的核心方法: - 1)创建Bean的实例:createBeanInstance(beanName, mbd, args)
在此后:applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName)
调用AutowiredAnnotationBeanPostProcessor的方法postProcessMergedBeanDefinition - 2)populateBean;给bean的各种属性赋值
- 3)initializeBean:初始化bean;
此时已将TestDao注入:
3.2 当作为InstantiationAwareBeanPostProcessor接口的实现时
InstantiationAwareBeanPostProcessor 方法,该步骤主要是populate bean ;通过 @Autowired 注解所引用的对象给 bean 的属性赋值。