AnnotationConfigApplicationConte

2020-10-28  本文已影响0人  Young_5942

测试代码:

//spring 配置类
@ComponentScan(value = {"com.y.user","com.y.product"})
public class SpringConfig {
}

package com.y.user;
public interface UserService {
    String getUser();
}

@Service
public class UserServiceImpl implements UserService {
    @Override
    public String getUser() {
        return "YOUNG";
    }
}


package com.y.product;
public interface ProductService {
    boolean order();
}

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private UserService userService;
    @Override
    public boolean order() {
        String user = userService.getUser();
        System.out.println(user + " complete order...");
        return true;
    }
}

@Test
public void testAnno() {
     AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
     annotationConfigApplicationContext.register(SpringConfig.class);
     annotationConfigApplicationContext.refresh();
     UserService userService = (UserService) annotationConfigApplicationContext.getBean("userServiceImpl");
     System.out.println(userService.getUser());
}

容器初始化

AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();

AnnotationConfigApplicationContext继承GenericApplicationContext,在初始化时候会先调用GenericApplicationContext的无参构造函数,实例化出一个DefaultListableBeanFactory,为后续的BeanDefinition注册做准备。

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

AnnotationConfigApplicationContext 的构造函数会初始化reader和scanner

    public AnnotationConfigApplicationContext() {
        this.reader = new AnnotatedBeanDefinitionReader(this);
        this.scanner = new ClassPathBeanDefinitionScanner(this);
    }
reader的初始化

reader的初始化过程中通过AnnotationConfigUtils注册几个注解处理器的Bean定义:
ConfigurationClassPostProcessor 是一个BeanFactoryPostProcessor处理器,容器启动时候对@Configuration注解的处理
AutowiredAnnotationBeanPostProcessor 是一个BeanPostProcessor处理器,对@Autowired注解处理
CommonAnnotationBeanPostProcessor 是一个BeanPostProcessor处理器,对@PostConstruct (初始化)和 @PreDestroy(移除)处理
DefaultEventListenerFactory 对@EventListener 处理
详细源码见:AnnotationConfigUtils#registerAnnotationConfigProcessors(this.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);
    }
scanner的初始化

scanner初始化过程

    public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,
            Environment environment, @Nullable ResourceLoader resourceLoader) {

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

        if (useDefaultFilters) {
            registerDefaultFilters();
        }
        setEnvironment(environment);
        setResourceLoader(resourceLoader);
    }

//过滤注解集合中增加 @Component注解,Component,Repository,Controller,Service都会被扫描到
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.trace("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.trace("JSR-330 'javax.inject.Named' annotation found and supported for component scanning");
        }
        catch (ClassNotFoundException ex) {
            // JSR-330 API not available - simply skip.
        }
    }

注册SpringConfig过程:annotationConfigApplicationContext.register(SpringConfig.class);

通过AnnotatedBeanDefinitionReader注册到DefaultListableBeanFactory的beanDefinitionMap中

@Override
    public void register(Class<?>... componentClasses) {
        Assert.notEmpty(componentClasses, "At least one component class must be specified");
        this.reader.register(componentClasses);
    }


<T> void doRegisterBean(Class<T> beanClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,
            @Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {

        AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
        if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
            return;
        }

        abd.setInstanceSupplier(instanceSupplier);
        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));
                }
            }
        }
        for (BeanDefinitionCustomizer customizer : definitionCustomizers) {
            customizer.customize(abd);
        }

        BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
        definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
        BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
    }
刷新容器annotationConfigApplicationContext.refresh()

调用refresh刷新容器,开始bean的实例化和依赖注入,会调用父类AbstractApplicationContext的refresh方法,
org.springframework.context.support.AbstractApplicationContext#refresh

@Override
    public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            // Prepare this context for refreshing.
            prepareRefresh();

            // Tell the subclass to refresh the internal bean factory.
            /**
             * 获得BeanFactory(首先得有这个才能创建Bean),默认DefaultListableBeanFactory
             * 同时先加载xml配置文件,加载BeanDefinition,并注册到BeanDefinitionRegistry(将id作为key,BeanDefinition作为value放入的map中)
             */
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

            // Prepare the bean factory for use in this context.
            /**
             * BeanFactory的预备工作,BeanFactory进行一些设置,比如context类加载器等。
             */
            prepareBeanFactory(beanFactory);

            try {
                // Allows post-processing of the bean factory in context subclasses.
                /**
                 * 获取BeanFactoryPostProcessor
                 */
                postProcessBeanFactory(beanFactory);

                // Invoke factory processors registered as beans in the context.
                /**
                 * 调用BeanFactoryPostProcessor#postProcessBeanFactory
                 */
                invokeBeanFactoryPostProcessors(beanFactory);

                // Register bean processors that intercept bean creation.
                /**
                 * 准备BeanPostProcessor,但是此时Bean还没有被创建,无法使用,后续使用
                 */
                registerBeanPostProcessors(beanFactory);

                // Initialize message source for this context.
                /**
                 * 国际化
                 */
                initMessageSource();

                // Initialize event multicaster for this context.

                initApplicationEventMulticaster();

                // Initialize other special beans in specific context subclasses.
                /**
                 * 子类重新这个方法,比如容器刷新的时候可以自定义逻辑:如创建Tomcat,jetty等web服务器
                 */
                onRefresh();

                // Check for listener beans and register them.
                /**
                 * 注册监听器
                 */
                registerListeners();

                // Instantiate all remaining (non-lazy-init) singletons.
                /**
                 * 初始化所有剩下的非懒加载的单例Bean
                 * 初始化创建非懒加载方式的单例Bean实例(未设置属性)
                 * 填充属性
                 * 初始化方法调用(比如调用afterPropertiesSet方法,init-method方法)
                 * 调用beanPostProcessor后置处理器对实例bean进行后置处理
                 */
                finishBeanFactoryInitialization(beanFactory);

                // Last step: publish corresponding event.
                /**
                 * 完成context的属性,主要调用了LiftCycleProcessor的onRefresh()方法,并且发布事件
                 */
                finishRefresh();
            }

            catch (BeansException ex) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Exception encountered during context initialization - " +
                            "cancelling refresh attempt: " + ex);
                }

                // Destroy already created singletons to avoid dangling resources.
                destroyBeans();

                // Reset 'active' flag.
                cancelRefresh(ex);

                // Propagate exception to caller.
                throw ex;
            }

            finally {
                // Reset common introspection caches in Spring's core, since we
                // might not ever need metadata for singleton beans anymore...
                resetCommonCaches();
            }
        }
    }

invokeBeanFactoryPostProcessors(beanFactory); 调用会触发org.springframework.context.annotation.ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry的调用,最终会通过ComponentScanAnnotationParser对@ComponentScan注解处理

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
        int registryId = System.identityHashCode(registry);
        if (this.registriesPostProcessed.contains(registryId)) {
            throw new IllegalStateException(
                    "postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
        }
        if (this.factoriesPostProcessed.contains(registryId)) {
            throw new IllegalStateException(
                    "postProcessBeanFactory already called on this post-processor against " + registry);
        }
        this.registriesPostProcessed.add(registryId);

        processConfigBeanDefinitions(registry);
    }

最终通过org.springframework.context.annotation.ComponentScanAnnotationParser#parse对@ComponentScan中定义的包进行扫描,加入到BeanDefinition定义中去。
经过上述处理后,DefaultListableBeanFactory的beanDefinitionMap中存在的定义有:
springConfig
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.event.internalEventListenerFactory
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
userServiceImpl
productServiceImpl

Bean的创建过程

refresh方法中的finishBeanFactoryInitialization()调用,触发bean的创建,通过DefaultListableBeanFactory的beanFactory.preInstantiateSingletons()方法创建Bean。
创建调用流程:


SequenceDiagram1.png

productServiceImpl中的Autowired注解在bean创建过程中的populateBean时被AutowiredAnnotationBeanPostProcessor这个后置处理器拦截处理,
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor#postProcessProperties
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.AutowiredFieldElement#inject
最终通过反射设置属性值


autowired.PNG

那么populateBean调用的时候,ProductServiceImpl中依赖的userService在哪里解析出来的呢?
doCreateBean的过程中有一个调用applyMergedBeanDefinitionPostProcessors,AutowiredAnnotationBeanPostProcessor会进行属性解析

protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof MergedBeanDefinitionPostProcessor) {
                MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
                bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
            }
        }
    }

使用AutowiredAnnotationBeanPostProcessor#postProcessMergedBeanDefinition 找出需要注入的属性

    @Override
    public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
        InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
        metadata.checkConfigMembers(beanDefinition);
    }

调用栈以及解析到的field属性


autowired.PNG
上一篇 下一篇

猜你喜欢

热点阅读