一: AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MainConfig.class); 为我们做了什么?
1.1)看下构造函数
>i1:org.springframework.context.annotation.AnnotationConfigApplicationContext#AnnotationConfigApplicationContext
i2>org.springframework.context.support.GenericApplicationContext#GenericApplicationContext() 调用父类的构造方法
i3>org.springframework.context.annotation.AnnotationConfigApplicationContext#AnnotationConfigApplicationContext() 自己的构造方法
i3.1>org.springframework.context.annotation.AnnotatedBeanDefinitionReader#AnnotatedBeanDefinitionReader 为bean定义读取器赋值
i3.1.1>org.springframework.context.annotation.AnnotatedBeanDefinitionReader#getOrCreateEnvironment 创建环境
i3.2>org.springframework.context.annotation.ConditionEvaluator 创建一个条件计算器对象
i3.2.1>this.registry = registry; 初始条件计算器的bean定义注册器
i3.2.2> this.beanFactory = deduceBeanFactory(registry); 初始化bean工厂
i3.2.3>this.environment = (environment != null ? environment : deduceEnvironment(registry)); 为环境对象赋值
i3.2.4> this.resourceLoader = (resourceLoader != null ? resourceLoader : deduceResourceLoader(registry)); 为资源加载器赋值
i3.3> AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);为容器中注册系统的bean定义信息
i4>: this.scanner = new ClassPathBeanDefinitionScanner(this); 创建类路径下的bean定义扫描器
i4.1>: org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider#registerDefaultFilters注册包扫描默认的规则
i4.2>:org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider#setEnvironment 设置环境
i4.3>org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider#setResourceLoader 设置资源加载器
i5>org.springframework.context.annotation.AnnotatedBeanDefinitionReader#register 使用i3.1步生成的bean定义读取器注册配置类
详细源码解析:
i1:org.springframework.context.annotation.AnnotationConfigApplicationContext#AnnotationConfigApplicationContext
创建IOC容器对象
创建
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
//调用无参的构造器,会调用父类的无参构造器
this();
//注册配置类
register(annotatedClasses);
//容器刷新
refresh();
}
i2>org.springframework.context.support.GenericApplicationContext#GenericApplicationContext() 调用父类的构造方法 生成一个IOC容器
public GenericApplicationContext() {
//创建IOC容器
this.beanFactory = new DefaultListableBeanFactory();
}
i3>org.springframework.context.annotation.AnnotationConfigApplicationContext#AnnotationConfigApplicationContext() 自己的构造方法
public AnnotationConfigApplicationContext() {
//为IOC容器赋值 AnnotatedBeanDefinitionReader(注解的Bean定义读取器)
this.reader = new AnnotatedBeanDefinitionReader(this);
//为IOC容器赋值 类路径下的bean定义扫描器
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
i3.1>org.springframework.context.annotation.AnnotatedBeanDefinitionReader#AnnotatedBeanDefinitionReader 为bean定义读取器赋值
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
this(registry, getOrCreateEnvironment(registry));
}
i3.1.1>org.springframework.context.annotation.AnnotatedBeanDefinitionReader#getOrCreateEnvironment 创建环境
private static Environment getOrCreateEnvironment(BeanDefinitionRegistry registry) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
if (registry instanceof EnvironmentCapable) {
return ((EnvironmentCapable) registry).getEnvironment();
}
return new StandardEnvironment();
}
i3.2>org.springframework.context.annotation.ConditionEvaluator 创建一个条件计算器对象
public ConditionContextImpl(BeanDefinitionRegistry registry, Environment environment, ResourceLoader resourceLoader) {
this.registry = registry;
this.beanFactory = deduceBeanFactory(registry);
this.environment = (environment != null ? environment : deduceEnvironment(registry));
this.resourceLoader = (resourceLoader != null ? resourceLoader : deduceResourceLoader(registry));
}
i3.3> AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);为容器中注册系统的bean定义信息
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
BeanDefinitionRegistry registry, Object source) {
//获取一个IOC容器
DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
if (beanFactory != null) {
if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
}
if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
}
}
Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<BeanDefinitionHolder>(8);
//注册一个配置类解析器的bean定义(ConfigurationClassPostProcessor)
if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
}
//设置AutoWired注解解析器的bean定义信息
if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
}
注册解析@Required 注解的处理器
if (!registry.containsBeanDefinition(REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(RequiredAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
}
//检查是否支持JSR250规范,如何支持注册 解析JSR250规范的注解
// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
}
//检查是否支持jpa,若支持注册解析jpa规范的注解
// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition();
try {
def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
AnnotationConfigUtils.class.getClassLoader()));
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
}
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
}
//注册解析@EventListener的注解
if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
}
if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
}
return beanDefs;
}
i4>: this.scanner = new ClassPathBeanDefinitionScanner(this); 创建类路径下的bean定义扫描器
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,
Environment environment, ResourceLoader resourceLoader) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
this.registry = registry;
//使用默认的扫描规则
if (useDefaultFilters) {
registerDefaultFilters();
}
//设置环境
setEnvironment(environment);
//设置资源加载器
setResourceLoader(resourceLoader);
}
i4.1>: org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider#registerDefaultFilters注册包扫描默认的规则
protected void registerDefaultFilters() {
//可以谢谢@Compent @Service @Repository @Controller @Aspectj
this.includeFilters.add(new AnnotationTypeFilter(Component.class));
ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader();
try {
//jsr250规范的组件
this.includeFilters.add(new AnnotationTypeFilter(
((Class<? extends Annotation>) ClassUtils.forName("javax.annotation.ManagedBean", cl)), false));
logger.debug("JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning");
}
catch (ClassNotFoundException ex) {
// JSR-250 1.1 API (as included in Java EE 6) not available - simply skip.
}
try {
//可以支持jsr330的注解
this.includeFilters.add(new AnnotationTypeFilter(
((Class<? extends Annotation>) ClassUtils.forName("javax.inject.Named", cl)), false));
logger.debug("JSR-330 'javax.inject.Named' annotation found and supported for component scanning");
}
catch (ClassNotFoundException ex) {
// JSR-330 API not available - simply skip.
}
}
i5>org.springframework.context.annotation.AnnotatedBeanDefinitionReader#register 使用i3.1步生成的bean定义读取器注册配置类
public void registerBean(Class<?> annotatedClass, String name, Class<? extends Annotation>... qualifiers) {
AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
return;
}
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
abd.setScope(scopeMetadata.getScopeName());
String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
if (qualifiers != null) {
for (Class<? extends Annotation> qualifier : qualifiers) {
if (Primary.class == qualifier) {
abd.setPrimary(true);
}
else if (Lazy.class == qualifier) {
abd.setLazyInit(true);
}
else {
abd.addQualifier(new AutowireCandidateQualifier(qualifier));
}
}
}
//注册自己传入的主配置类bean定义到容器中
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}