当前位置:   article > 正文

spring源码分析系列-spring启动流程(包含bean的生命周期)上_startupstep beancreation

startupstep beancreation

目录

1. 基本环境:

2. 进入源码

2.1 分析this()方法

2. register方法


        真是万事开头难,一点不假。计划着写一个spring源码分析的系列文章,但是每每提笔又不知道该用什么样的开场白比较合适,很是无奈。实话讲,阅读源码的过程很漫长甚至有点痛苦,但是每次学到些什么又会有莫名的满足,从这篇文章开始,我们一点点一步步来揭开spring源码的神秘面纱,我们切勿急躁,怀着一颗虔诚的心踏踏实实的学,就像是流水不争先只争个滔滔不绝。

        闲言少叙,言归正传。spring启动流程我准备分为上中下三篇,本篇重点内容包括配置类转beanDefinition并注册到spring容器的过程,ConfigurationClassPostProcessor这个最重要的后置处理器的注册过程。注意哦,本篇内容只会介绍它的注册过程具体解析过程在下一篇。

1. 基本环境:

(1) 通过包扫描交给spring托管的IndexDao类:

  1. @Component
  2. public class IndexDao {
  3. public void query(){
  4. System.out.println("indexDao query...");
  5. }
  6. }

(2) 通过@Import交给spring托管的IndexDao2类: 

  1. public class IndexDao2 {
  2. public void query(){
  3. System.out.println("indexDao2 query...");
  4. }
  5. }

(3) 核心配置类IocConfig:

  1. @Configuration
  2. @ComponentScan("com.zlb.ioc")
  3. @Import(MySelector.class)
  4. public class IocConfig {
  5. }

(4) MySelector类,重写方法返回的正式IndexDao2的全限定名:

  1. public class MySelector implements ImportSelector {
  2. @Override
  3. public String[] selectImports(AnnotationMetadata importingClassMetadata) {
  4. return new String[]{IndexDao2.class.getName()};
  5. }
  6. }

(5) 最后,主测试类:

  1. public class Demo {
  2. public static void main(String[] args) {
  3. AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(IocConfig.class);
  4. IndexDao dao = context.getBean(IndexDao.class);
  5. IndexDao2 dao2 = context.getBean(IndexDao2.class);
  6. dao.query();
  7. dao2.query();
  8. }
  9. }

2. 进入源码

进入到创建上下文对象的构造方法中:

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(IocConfig.class);
  1. public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
  2. this();
  3. register(componentClasses);
  4. refresh();
  5. }

2.1 分析this()方法

这里我们要注意一下,在执行this方法之前java会首先执行父类的无参构造,就是

GenericApplicationContext的GenericApplicationContext()方法:
  1. public GenericApplicationContext() {
  2. this.beanFactory = new DefaultListableBeanFactory();
  3. }

注:我们常说的bean工厂正是上边这个货DefaultListableBeanFactory,它也是我们spring上下文对象的一个属性。

接下来我们再进入到this方法:

  1. public AnnotationConfigApplicationContext() {
  2. StartupStep createAnnotatedBeanDefReader = this.getApplicationStartup().start("spring.context.annotated-bean-reader.create");
  3. //这个构造函数主要做了两件事
  4. // 1.AnnotatedBeanDefinitionReader的registry赋值
  5. // 2.向beanFactory中注册ConfigurationClassPostProcessor
  6. // 进到这行
  7. this.reader = new AnnotatedBeanDefinitionReader(this);
  8. createAnnotatedBeanDefReader.end();
  9. this.scanner = new ClassPathBeanDefinitionScanner(this);
  10. }
  1. public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
  2. //进到这行
  3. this(registry, getOrCreateEnvironment(registry));
  4. }
  1. public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
  2. Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
  3. Assert.notNull(environment, "Environment must not be null");
  4. //给registry属性赋值 后边注册自定义Config类的时候会用到
  5. this.registry = registry;
  6. this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
  7. //向beanFactory中注册ConfigurationClassPostProcessor 进入这个方法
  8. AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
  9. }
  1. public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) {
  2. //进到这个方法
  3. registerAnnotationConfigProcessors(registry, null);
  4. }
  1. public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
  2. BeanDefinitionRegistry registry, @Nullable Object source) {
  3. //从registry(上下文)中获取beanFactory
  4. DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
  5. //给beanFactory设置两个属性 暂时不用管
  6. if (beanFactory != null) {
  7. if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
  8. beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
  9. }
  10. if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
  11. beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
  12. }
  13. }
  14. Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);
  15. //向beanFactory中注册ConfigurationClassPostProcessor
  16. //这个if块最重要其他不用管
  17. if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  18. //将ConfigurationClassPostProcessor转换成beanDefinition
  19. RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
  20. def.setSource(source);
  21. //registerPostProcessor()这个方法中注册ConfigurationClassPostProcessor
  22. //进到registerPostProcessor这个方法
  23. beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
  24. }
  25. if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  26. RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
  27. def.setSource(source);
  28. beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
  29. }
  30. // Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
  31. if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  32. RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
  33. def.setSource(source);
  34. beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
  35. }
  36. // Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
  37. if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  38. RootBeanDefinition def = new RootBeanDefinition();
  39. try {
  40. def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
  41. AnnotationConfigUtils.class.getClassLoader()));
  42. }
  43. catch (ClassNotFoundException ex) {
  44. throw new IllegalStateException(
  45. "Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
  46. }
  47. def.setSource(source);
  48. beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
  49. }
  50. if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
  51. RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
  52. def.setSource(source);
  53. beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
  54. }
  55. if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
  56. RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
  57. def.setSource(source);
  58. beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
  59. }
  60. return beanDefs;
  61. }
  1. private static BeanDefinitionHolder registerPostProcessor(
  2. BeanDefinitionRegistry registry, RootBeanDefinition definition, String beanName) {
  3. definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
  4. // 这个方法就是在注册了
  5. // registry就是我们的bean工厂DefaultListableBeanFactory
  6. // beanName就是org.springframework.context.annotation.internalConfigurationAnnotationProcessor
  7. // definition就是根据ConfigurationClassPostProcessor转换来的beanDefinition
  8. // 那到底注册是干啥呢 我们继续
  9. registry.registerBeanDefinition(beanName, definition);
  10. return new BeanDefinitionHolder(definition, beanName);
  11. }

注:注意哦,registry默认实现是DefaultListableBeanFactory,我们要进入到这个实现类的registerBeanDefinition()方法。

  1. @Override
  2. public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
  3. throws BeanDefinitionStoreException {
  4. Assert.hasText(beanName, "Bean name must not be empty");
  5. Assert.notNull(beanDefinition, "BeanDefinition must not be null");
  6. //校验 不用管
  7. if (beanDefinition instanceof AbstractBeanDefinition) {
  8. try {
  9. ((AbstractBeanDefinition) beanDefinition).validate();
  10. }
  11. catch (BeanDefinitionValidationException ex) {
  12. throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
  13. "Validation of bean definition failed", ex);
  14. }
  15. }
  16. BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
  17. //existingDefinition = null 不会进这个if
  18. if (existingDefinition != null) {
  19. if (!isAllowBeanDefinitionOverriding()) {
  20. throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
  21. }
  22. else if (existingDefinition.getRole() < beanDefinition.getRole()) {
  23. // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
  24. if (logger.isInfoEnabled()) {
  25. logger.info("Overriding user-defined bean definition for bean '" + beanName +
  26. "' with a framework-generated bean definition: replacing [" +
  27. existingDefinition + "] with [" + beanDefinition + "]");
  28. }
  29. }
  30. else if (!beanDefinition.equals(existingDefinition)) {
  31. if (logger.isDebugEnabled()) {
  32. logger.debug("Overriding bean definition for bean '" + beanName +
  33. "' with a different definition: replacing [" + existingDefinition +
  34. "] with [" + beanDefinition + "]");
  35. }
  36. }
  37. else {
  38. if (logger.isTraceEnabled()) {
  39. logger.trace("Overriding bean definition for bean '" + beanName +
  40. "' with an equivalent definition: replacing [" + existingDefinition +
  41. "] with [" + beanDefinition + "]");
  42. }
  43. }
  44. this.beanDefinitionMap.put(beanName, beanDefinition);
  45. }
  46. else {
  47. //不会进这个if
  48. if (hasBeanCreationStarted()) {
  49. // Cannot modify startup-time collection elements anymore (for stable iteration)
  50. synchronized (this.beanDefinitionMap) {
  51. this.beanDefinitionMap.put(beanName, beanDefinition);
  52. List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
  53. updatedDefinitions.addAll(this.beanDefinitionNames);
  54. updatedDefinitions.add(beanName);
  55. this.beanDefinitionNames = updatedDefinitions;
  56. removeManualSingletonName(beanName);
  57. }
  58. }
  59. else {
  60. // Still in startup registration phase
  61. //核心部分:注册beanDefinition
  62. //其实就是向bean工厂的beanDefinitionMap中put个beanDefinition
  63. //还有就是向bean工厂的beanDefinitionNames集合中添加一个名字而已
  64. this.beanDefinitionMap.put(beanName, beanDefinition);
  65. this.beanDefinitionNames.add(beanName);
  66. removeManualSingletonName(beanName);
  67. }
  68. this.frozenBeanDefinitionNames = null;
  69. }
  70. if (existingDefinition != null || containsSingleton(beanName)) {
  71. resetBeanDefinition(beanName);
  72. }
  73. else if (isConfigurationFrozen()) {
  74. clearByTypeCache();
  75. }
  76. }

那么行棋至此,this方法的主要逻辑我们已经看完了,小小总结一下this()方法究竟干了些啥呢?其实非常简单就干了两件事:

        1. new了一个bean工厂的默认实现DefaultListableBeanFactory并赋值给了spring上下文的成员变量。

        2. new了一个AnnotatedBeanDefinitionReader对象也赋值给了spring上下文的成员变量。但是这个不太重要。

        3. 在new AnnotatedBeanDefinitionReader对象过程中向bean工厂中注册了一个特别重要的类ConfigurationClassPostProcessor,这个类极其极其重要!具体作用我们后面会说到,先请大家牢记此类。

2. register方法

接下来我们分析register()方法。这个方法很简单只做了一件事,那就是把我们的配置类注册给spring。

  1. public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
  2. this();
  3. //进到这个方法
  4. register(componentClasses);
  5. refresh();
  6. }
  1. @Override
  2. public void register(Class<?>... componentClasses) {
  3. Assert.notEmpty(componentClasses, "At least one component class must be specified");
  4. StartupStep registerComponentClass = this.getApplicationStartup().start("spring.context.component-classes.register")
  5. .tag("classes", () -> Arrays.toString(componentClasses));
  6. //参数componentClasses其实就是我们的配置类
  7. //进到这行
  8. this.reader.register(componentClasses);
  9. registerComponentClass.end();
  10. }
  1. public void register(Class<?>... componentClasses) {
  2. for (Class<?> componentClass : componentClasses) {
  3. //配置类可以传多个 但是我们只有一个 go on
  4. registerBean(componentClass);
  5. }
  6. }
  1. public void registerBean(Class<?> beanClass) {
  2. //继续
  3. doRegisterBean(beanClass, null, null, null, null);
  4. }
  1. private <T> void doRegisterBean(Class<T> beanClass, @Nullable String name,
  2. @Nullable Class<? extends Annotation>[] qualifiers, @Nullable Supplier<T> supplier,
  3. @Nullable BeanDefinitionCustomizer[] customizers) {
  4. //把我们的配置类转成beanDefinition
  5. AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
  6. if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
  7. return;
  8. }
  9. abd.setInstanceSupplier(supplier);
  10. ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
  11. abd.setScope(scopeMetadata.getScopeName());
  12. String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
  13. AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
  14. if (qualifiers != null) {
  15. for (Class<? extends Annotation> qualifier : qualifiers) {
  16. if (Primary.class == qualifier) {
  17. abd.setPrimary(true);
  18. }
  19. else if (Lazy.class == qualifier) {
  20. abd.setLazyInit(true);
  21. }
  22. else {
  23. abd.addQualifier(new AutowireCandidateQualifier(qualifier));
  24. }
  25. }
  26. }
  27. if (customizers != null) {
  28. for (BeanDefinitionCustomizer customizer : customizers) {
  29. customizer.customize(abd);
  30. }
  31. }
  32. //对beanDefinition和beanName再做一次封装 包装成一个holder
  33. BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
  34. definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
  35. //注册beanDefinition正是在这儿完成的 进去这行代码
  36. BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
  37. }
  1. public static void registerBeanDefinition(
  2. BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
  3. throws BeanDefinitionStoreException {
  4. // Register bean definition under primary name.
  5. String beanName = definitionHolder.getBeanName();
  6. //注册beanDefinition在这儿
  7. //registry默认实现是DefaultListableBeanFactory
  8. registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
  9. // Register aliases for bean name, if any.
  10. String[] aliases = definitionHolder.getAliases();
  11. if (aliases != null) {
  12. for (String alias : aliases) {
  13. registry.registerAlias(beanName, alias);
  14. }
  15. }
  16. }
  1. @Override
  2. public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
  3. throws BeanDefinitionStoreException {
  4. Assert.hasText(beanName, "Bean name must not be empty");
  5. Assert.notNull(beanDefinition, "BeanDefinition must not be null");
  6. //校验 不用管
  7. if (beanDefinition instanceof AbstractBeanDefinition) {
  8. try {
  9. ((AbstractBeanDefinition) beanDefinition).validate();
  10. }
  11. catch (BeanDefinitionValidationException ex) {
  12. throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
  13. "Validation of bean definition failed", ex);
  14. }
  15. }
  16. BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
  17. //existingDefinition = null 不会进这个if
  18. if (existingDefinition != null) {
  19. if (!isAllowBeanDefinitionOverriding()) {
  20. throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
  21. }
  22. else if (existingDefinition.getRole() < beanDefinition.getRole()) {
  23. // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
  24. if (logger.isInfoEnabled()) {
  25. logger.info("Overriding user-defined bean definition for bean '" + beanName +
  26. "' with a framework-generated bean definition: replacing [" +
  27. existingDefinition + "] with [" + beanDefinition + "]");
  28. }
  29. }
  30. else if (!beanDefinition.equals(existingDefinition)) {
  31. if (logger.isDebugEnabled()) {
  32. logger.debug("Overriding bean definition for bean '" + beanName +
  33. "' with a different definition: replacing [" + existingDefinition +
  34. "] with [" + beanDefinition + "]");
  35. }
  36. }
  37. else {
  38. if (logger.isTraceEnabled()) {
  39. logger.trace("Overriding bean definition for bean '" + beanName +
  40. "' with an equivalent definition: replacing [" + existingDefinition +
  41. "] with [" + beanDefinition + "]");
  42. }
  43. }
  44. this.beanDefinitionMap.put(beanName, beanDefinition);
  45. }
  46. else {
  47. //不会进这个if
  48. if (hasBeanCreationStarted()) {
  49. // Cannot modify startup-time collection elements anymore (for stable iteration)
  50. synchronized (this.beanDefinitionMap) {
  51. this.beanDefinitionMap.put(beanName, beanDefinition);
  52. List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
  53. updatedDefinitions.addAll(this.beanDefinitionNames);
  54. updatedDefinitions.add(beanName);
  55. this.beanDefinitionNames = updatedDefinitions;
  56. removeManualSingletonName(beanName);
  57. }
  58. }
  59. else {
  60. // Still in startup registration phase
  61. //核心部分:注册beanDefinition
  62. //其实就是向bean工厂的beanDefinitionMap中put个beanDefinition
  63. //还有就是向bean工厂的beanDefinitionNames集合中添加一个名字而已
  64. this.beanDefinitionMap.put(beanName, beanDefinition);
  65. this.beanDefinitionNames.add(beanName);
  66. removeManualSingletonName(beanName);
  67. }
  68. this.frozenBeanDefinitionNames = null;
  69. }
  70. if (existingDefinition != null || containsSingleton(beanName)) {
  71. resetBeanDefinition(beanName);
  72. }
  73. else if (isConfigurationFrozen()) {
  74. clearByTypeCache();
  75. }
  76. }

截止到这里,我们已经把配置类转换成了beanDefinition并且注册给了spring容器。再强调一次,所谓注册通俗点说就是把我们的类转换成beanDefinition然后放到beanFactory的集合里边,也就是这个:

this.beanDefinitionMap.put(beanName, beanDefinition);
this.beanDefinitionNames.add(beanName);

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/609329
推荐阅读
相关标签
  

闽ICP备14008679号