spring boot实战(第八篇)上下文的创建

扫码关注公众号:Java 技术驿站

发送:vip
将链接复制到本浏览器,永久解锁本站全部文章

【公众号:Java 技术驿站】 【加作者微信交流技术,拉技术群】

前言

本篇主要讲解spring boot上下文的创建,为后续源码的解读打下铺垫

ApplicationContext

在run方法中执行

         context  = createApplicationContext(); 

创建上下文

    protected ConfigurableApplicationContext createApplicationContext() {
            Class<?> contextClass = this.applicationContextClass;
            if (contextClass == null) {
                try {
                    contextClass = Class
                            .forName(this.webEnvironment ? DEFAULT_WEB_CONTEXT_CLASS
                                    : DEFAULT_CONTEXT_CLASS);
                }
                catch (ClassNotFoundException ex) {
                    throw new IllegalStateException(
                            "Unable create a default ApplicationContext, "
                                    + "please specify an ApplicationContextClass", ex);
                }
            }
            return (ConfigurableApplicationContext) BeanUtils.instantiate(contextClass);
        }

创建DEFAULT_WEB_CONTEXT_CLASS –>AnnotationConfigEmbeddedWebApplicationContext实例,创建实例 调用构造方法,首先需要分清楚spring boot中多上下文之间的关联关系,

![《spring boot实战(第八篇)上下文的创建》][spring boot]20191102100603\_1.png

结构相对比较复杂一些

执行AnnotationConfigEmbeddedWebApplicationContext构造方法

    public AnnotationConfigEmbeddedWebApplicationContext() {
            this.reader = new AnnotatedBeanDefinitionReader(this);
            this.scanner = new ClassPathBeanDefinitionScanner(this);
        }

实例化AnnotatedBeanDefinitionReader以及ClassPathBeanDefinitionScanner

  • 实例化AnnotatedBeanDefinitionReader
    public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
            this(registry, getOrCreateEnvironment(registry));
        }

调用

    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);
        }

实例化 ConditionEvaluator,将其属性ConditionContextImpl赋值

    AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);

实现如下:

    public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
                BeanDefinitionRegistry registry, Object source) {

            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>(4);

            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));
            }

            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));
            }

            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));
            }

            // 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));
            }

            // 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));
            }

            return beanDefs;
        }

这段代码比较长,分开来分析

    DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);

获取beanFactory信息

    private static DefaultListableBeanFactory unwrapDefaultListableBeanFactory(BeanDefinitionRegistry registry) {
            if (registry instanceof DefaultListableBeanFactory) {
                return (DefaultListableBeanFactory) registry;
            }
            else if (registry instanceof GenericApplicationContext) {
                return ((GenericApplicationContext) registry).getDefaultListableBeanFactory();
            }
            else {
                return null;
            }
        }

代码执行到
registry
instanceof GenericApplicationContext(通过类继承结构可得到),随后调用GenericApplicationContext#
getDefaultListableBeanFactory()方法,GenericApplicationContext在构造方法中实例化了属性beanFactory的值
为DefaultListableBeanFactory:

    public GenericApplicationContext() {
            this.beanFactory = new DefaultListableBeanFactory();
        }

其构造优先于AnnotationConfigEmbeddedWebApplicationContext构造方法执行。

以上获得了BeanFactory信息

BeanDefinition

在获取完BeanFactory以后,代码中涉及到了bean定义信息,首先来看下BeanDefinition相关信息

![《spring boot实战(第八篇)上下文的创建》][spring boot]

  • BeanDefinition 设计bean相关信息
  • BeanDefinitionHolder 封装bean定义相关信息,以及bean名称、别名等
  • BeanDefinitionRegistry 持有所有注册的bean相关信息
    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));
            }

这段代码以及其紧跟的代码为创建若干bean,其中

    registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)

表示注册名称为org.springframework.context.annotation.internalConfigurationAnnotationProcessor,beanClass 对应为ConfigurationClassPostProcessor的bean

Bean注册

    private static BeanDefinitionHolder registerPostProcessor(
                BeanDefinitionRegistry registry, RootBeanDefinition definition, String beanName) {

            definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
            registry.registerBeanDefinition(beanName, definition);
            return new BeanDefinitionHolder(definition, beanName);
        }

其中
registry.registerBeanDefinition(
beanName,
definition)调用GenericApplicationContext中的方法

    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
                throws BeanDefinitionStoreException {

            this.beanFactory.registerBeanDefinition(beanName, beanDefinition);
        }

其中
this
.beanFactory为DefaultListableBeanFactory实例

    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
                throws BeanDefinitionStoreException {

            Assert.hasText(beanName, "Bean name must not be empty");
            Assert.notNull(beanDefinition, "BeanDefinition must not be null");

            if (beanDefinition instanceof AbstractBeanDefinition) {
                try {
                    ((AbstractBeanDefinition) beanDefinition).validate();
                }
                catch (BeanDefinitionValidationException ex) {
                    throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
                            "Validation of bean definition failed", ex);
                }
            }

            BeanDefinition oldBeanDefinition;

            oldBeanDefinition = this.beanDefinitionMap.get(beanName);
            if (oldBeanDefinition != null) {
                if (!isAllowBeanDefinitionOverriding()) {
                    throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
                            "Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +
                            "': There is already [" + oldBeanDefinition + "] bound.");
                }
                else if (oldBeanDefinition.getRole() < beanDefinition.getRole()) {
                    // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
                    if (this.logger.isWarnEnabled()) {
                        this.logger.warn("Overriding user-defined bean definition for bean '" + beanName +
                                "' with a framework-generated bean definition: replacing [" +
                                oldBeanDefinition + "] with [" + beanDefinition + "]");
                    }
                }
                else {
                    if (this.logger.isInfoEnabled()) {
                        this.logger.info("Overriding bean definition for bean '" + beanName +
                                "': replacing [" + oldBeanDefinition + "] with [" + beanDefinition + "]");
                    }
                }
            }
            else {
                this.beanDefinitionNames.add(beanName);
                this.manualSingletonNames.remove(beanName);
                this.frozenBeanDefinitionNames = null;
            }
            this.beanDefinitionMap.put(beanName, beanDefinition);

            if (oldBeanDefinition != null || containsSingleton(beanName)) {
                resetBeanDefinition(beanName);
            }
        }

以上方法完成了bean的注册;

首先完成校验

    ((AbstractBeanDefinition) beanDefinition).validate();
    oldBeanDefinition = this.beanDefinitionMap.get(beanName);

表示从map中获取bean,初始肯定无法获取,进入如下程序

    <span style="white-space:pre">          </span>this.beanDefinitionNames.add(beanName);
                this.manualSingletonNames.remove(beanName);
                this.frozenBeanDefinitionNames = null;<p class="p1"><span class="s1"><span style="white-space:pre">         </span>this</span><span class="s2">.</span><span class="s3">beanDefinitionMap</span><span class="s2">.put(</span>beanName<span class="s2">, </span>beanDefinition<span class="s2">);</span></p>

完成bean信息的存储。

这里顺便解释下,在从map中获取到bean时表示bean已经注册,则会判断是否可以覆盖oldBean,也需要判断bean对应的Role级别

以上完成了AnnotatedBeanDefinitionReader实例的构造

接下来为ClassPathBeanDefinitionScanner实例的创建

    public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters) {
            this(registry, useDefaultFilters, getOrCreateEnvironment(registry));
        }

调用

    public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters, Environment environment) {
            super(useDefaultFilters, environment);

            Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
            this.registry = registry;

            // Determine ResourceLoader to use.
            if (this.registry instanceof ResourceLoader) {
                setResourceLoader((ResourceLoader) this.registry);
            }
        }

调用super构造

    public ClassPathScanningCandidateComponentProvider(boolean useDefaultFilters, Environment environment) {
            if (useDefaultFilters) {
                registerDefaultFilters();
            }
            Assert.notNull(environment, "Environment must not be null");
            this.environment = environment;
        }

在该方法中完成了environment的赋值以及为ClassPathScanningCandidateComponentProvider完成了默认过滤器的注册

    protected void registerDefaultFilters() {
            this.includeFilters.add(new AnnotationTypeFilter(Component.class));
            ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader();
            try {
                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 {
                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.
            }
        }

将Component、ManagedBean、Named注解增加到包含过滤规则中。

    setResourceLoader((ResourceLoader) this.registry)
    public void setResourceLoader(ResourceLoader resourceLoader) {
            this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
            this.metadataReaderFactory = new CachingMetadataReaderFactory(resourceLoader);
        }

完成对
resourcePatternResolver以及
metadataReaderFactory的赋值操作。

以上完成了上下文的创建

小结

在创建上下文时 完成了BeanFactory的创建,注册了特定的bean信息,完成了各种属性变量的初始化操作,各属性值将在后续文章中依次讲述。

转载请注明
http://blog.csdn.net/liaokailin/article/details/48186331

欢迎关注,您的肯定是对我最大的支持

20191102100603\_2.png

[spring boot]:


来源:http://ddrv.cn

赞(0) 打赏
版权归原创作者所有,任何形式的转载请联系博主:daming_90:Java 技术驿站 » spring boot实战(第八篇)上下文的创建

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏