Questions:

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MainConfig.class); 为我们做了什么?

看下列构造函数

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容器对象

  1. //创建
  2. public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
  3. //调用无参的构造器,会调用父类的无参构造器
  4. this();
  5. //注册配置类
  6. register(annotatedClasses);
  7. //容器刷新
  8. refresh();
  9. }

i2>org.springframework.context.support.GenericApplicationContext#GenericApplicationContext()

调用父类的构造方法 生成一个IOC容器

  1. public GenericApplicationContext() {
  2. //创建IOC容器
  3. this.beanFactory = new DefaultListableBeanFactory();
  4. }

i3>org.springframework.context.annotation.AnnotationConfigApplicationContext#AnnotationConfigApplicationContext()

自己的构造方法

  1. public AnnotationConfigApplicationContext() {
  2. //为IOC容器赋值 AnnotatedBeanDefinitionReader(注解的Bean定义读取器)
  3. this.reader = new AnnotatedBeanDefinitionReader(this);
  4. //为IOC容器赋值 类路径下的bean定义扫描器
  5. this.scanner = new ClassPathBeanDefinitionScanner(this);
  6. }

i3.1>org.springframework.context.annotation.AnnotatedBeanDefinitionReader#AnnotatedBeanDefinitionReader

为bean定义读取器赋值

  1. public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
  2. this(registry, getOrCreateEnvironment(registry));
  3. }

i3.1.1>org.springframework.context.annotation.AnnotatedBeanDefinitionReader#getOrCreateEnvironment

创建环境

  1. private static Environment getOrCreateEnvironment(BeanDefinitionRegistry registry) {
  2. Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
  3. if (registry instanceof EnvironmentCapable) {
  4. return ((EnvironmentCapable) registry).getEnvironment();
  5. }
  6. return new StandardEnvironment();
  7. }

i3.2>org.springframework.context.annotation.ConditionEvaluator

创建一个条件计算器对象

  1. public ConditionContextImpl(BeanDefinitionRegistry registry,
  2. Environment environment, ResourceLoader resourceLoader) {
  3. this.registry = registry;
  4. this.beanFactory = deduceBeanFactory(registry);
  5. this.environment = (environment != null ? environment : deduceEnvironment(registry));
  6. this.resourceLoader =
  7. (resourceLoader != null ? resourceLoader : deduceResourceLoader(registry));
  8. }

i3.3> AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);

为容器中注册系统的bean定义信息

  1. public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
  2. BeanDefinitionRegistry registry, Object source) {
  3. //获取一个IOC容器
  4. DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
  5. if (beanFactory != null) {
  6. if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
  7. beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
  8. }
  9. if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
  10. beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
  11. }
  12. }
  13. Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<BeanDefinitionHolder>(8);
  14. //注册一个配置类解析器的bean定义(ConfigurationClassPostProcessor)
  15. if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  16. RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
  17. def.setSource(source);
  18. beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
  19. }
  20. //设置AutoWired注解解析器的bean定义信息
  21. if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  22. RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
  23. def.setSource(source);
  24. beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
  25. }
  26. 注册解析@Required 注解的处理器
  27. if (!registry.containsBeanDefinition(REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  28. RootBeanDefinition def = new RootBeanDefinition(RequiredAnnotationBeanPostProcessor.class);
  29. def.setSource(source);
  30. beanDefs.add(registerPostProcessor(registry, def, REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
  31. }
  32. //检查是否支持JSR250规范,如何支持注册 解析JSR250规范的注解
  33. // Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
  34. if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  35. RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
  36. def.setSource(source);
  37. beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
  38. }
  39. //检查是否支持jpa,若支持注册解析jpa规范的注解
  40. // Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
  41. if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  42. RootBeanDefinition def = new RootBeanDefinition();
  43. try {
  44. def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
  45. AnnotationConfigUtils.class.getClassLoader()));
  46. }
  47. catch (ClassNotFoundException ex) {
  48. throw new IllegalStateException(
  49. "Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
  50. }
  51. def.setSource(source);
  52. beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
  53. }
  54. //注册解析@EventListener的注解
  55. if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
  56. RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
  57. def.setSource(source);
  58. beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
  59. }
  60. if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
  61. RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
  62. def.setSource(source);
  63. beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
  64. }
  65. return beanDefs;
  66. }

i4>: this.scanner = new ClassPathBeanDefinitionScanner(this);

创建类路径下的bean定义扫描器

  1. public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry,
  2. boolean useDefaultFilters, Environment environment, ResourceLoader resourceLoader) {
  3. Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
  4. this.registry = registry;
  5. //使用默认的扫描规则
  6. if (useDefaultFilters) {
  7. registerDefaultFilters();
  8. }
  9. //设置环境
  10. setEnvironment(environment);
  11. //设置资源加载器
  12. setResourceLoader(resourceLoader);
  13. }

i4.1>: org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider#registerDefaultFilters

注册包扫描默认的规则

  1. protected void registerDefaultFilters() {
  2. //可以谢谢@Compent @Service @Repository @Controller @Aspectj
  3. this.includeFilters.add(new AnnotationTypeFilter(Component.class));
  4. ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader();
  5. try {
  6. //jsr250规范的组件
  7. this.includeFilters.add(new AnnotationTypeFilter(
  8. ((Class<? extends Annotation>) ClassUtils.forName("javax.annotation.ManagedBean", cl)), false));
  9. logger.debug("JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning");
  10. }
  11. catch (ClassNotFoundException ex) {
  12. // JSR-250 1.1 API (as included in Java EE 6) not available - simply skip.
  13. }
  14. try {
  15. //可以支持jsr330的注解
  16. this.includeFilters.add(new AnnotationTypeFilter(
  17. ((Class<? extends Annotation>) ClassUtils.forName("javax.inject.Named", cl)), false));
  18. logger.debug("JSR-330 'javax.inject.Named' annotation found and supported for component scanning");
  19. }
  20. catch (ClassNotFoundException ex) {
  21. // JSR-330 API not available - simply skip.
  22. }
  23. }

i5>org.springframework.context.annotation.AnnotatedBeanDefinitionReader#register

使用i3.1步生成的bean定义读取器注册配置类

  1. public void registerBean(Class<?> annotatedClass, String name, Class<? extends Annotation>... qualifiers) {
  2. AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
  3. if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
  4. return;
  5. }
  6. ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
  7. abd.setScope(scopeMetadata.getScopeName());
  8. String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
  9. AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
  10. if (qualifiers != null) {
  11. for (Class<? extends Annotation> qualifier : qualifiers) {
  12. if (Primary.class == qualifier) {
  13. abd.setPrimary(true);
  14. }
  15. else if (Lazy.class == qualifier) {
  16. abd.setLazyInit(true);
  17. }
  18. else {
  19. abd.addQualifier(new AutowireCandidateQualifier(qualifier));
  20. }
  21. }
  22. }
  23. //注册自己传入的主配置类bean定义到容器中
  24. BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
  25. definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
  26. BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
  27. }