spring的注解驱动和自动装配

41次阅读

共计 25068 个字符,预计需要花费 63 分钟才能阅读完成。

Spring IOC 容器启动阶段.

SpringApplication.run 方法. createApplicationContext() 阶段, 依据 WebType 创建了 AnnotationConfigServletWebServerApplicationContext 类. 同时初始化了两个读取器.

  1. AnnotatedBeanDefinitionReader. 基于注解
  2. ClassPathBeanDefinitionScanner. 基于 XML 的

AnnotatedBeanDefinitionReader 的构造器
<!– more –>

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);
    }
    // 在创建 ApplicationContext 的时候, 会注册几个 BeanFactoryPostProcessor
    public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(BeanDefinitionRegistry registry, @Nullable Object source) {
        
        // 获取 BeanFactory. DefaultListableBeanFactory 本身就是 BeanDefinitionRegistry 的实现类. 所以可以注册
        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<>(8);

        if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
            // 注册自动装配的核心类   优先级为 LOWEST_PRECEDENCE
            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)) {
            // 注册 Autowire 注解的核心类 优先级为 LOWEST_PRECEDENCE-2
            RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
            def.setSource(source);
            beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
        }

        // Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
        if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {

            //@PostConstruct @PreDestroy @Resource @WebServiceRef @WebServiceClient 的核心类 优先级为 LOWEST_PRECEDENCE-3
            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));
        }

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

由此我们知道了他们的执行顺序 CommonAnnotationBeanPostProcessor->AutowiredAnnotationBeanPostProcessor->AnnotationAwareOrderComparator

在 run 方法的时候 我们将启动类传入. 作为 primarySources. 它的加载好和注册在 prepareContext() 阶段 load() 方法

protected void load(ApplicationContext context, Object[] sources) {if (logger.isDebugEnabled()) {logger.debug("Loading source" + StringUtils.arrayToCommaDelimitedString(sources));
        }
        // 这里的注册器 依旧是 DefaultListableBeanFactory.
        BeanDefinitionLoader loader = createBeanDefinitionLoader(getBeanDefinitionRegistry(context), sources);
        if (this.beanNameGenerator != null) {loader.setBeanNameGenerator(this.beanNameGenerator);
        }
        if (this.resourceLoader != null) {loader.setResourceLoader(this.resourceLoader);
        }
        if (this.environment != null) {loader.setEnvironment(this.environment);
        }
        loader.load();}

    public int load() {
        int count = 0;
        for (Object source : this.sources) {count += load(source);
        }
        return count;
    }

    private int load(Object source) {Assert.notNull(source, "Source must not be null");
        if (source instanceof Class<?>) {return load((Class<?>) source);
        }
        if (source instanceof Resource) {return load((Resource) source);
        }
        if (source instanceof Package) {return load((Package) source);
        }
        if (source instanceof CharSequence) {return load((CharSequence) source);
        }
        throw new IllegalArgumentException("Invalid source type" + source.getClass());
    }

    private int load(Class<?> source) {if (isGroovyPresent() && GroovyBeanDefinitionSource.class.isAssignableFrom(source)) {// Any GroovyLoaders added in beans{} DSL can contribute beans here
            GroovyBeanDefinitionSource loader = BeanUtils.instantiateClass(source, GroovyBeanDefinitionSource.class);
            load(loader);
        }
        if (isComponent(source)) {
            // 在这里注册. AnnotatedGenericBeanDefinition
            this.annotatedReader.register(source);
            return 1;
        }
        return 0;
    }

ConfigurationClassPostProcessor 的执行

ConfigurationClassPostProcessor 这个的执行节点 就不介绍了. 具体逻辑在 AbstractApplicationContext#refresh()invokeBeanFactoryPostProcessors() 方法里.

ConfigurationClassPostProcessor 是 BeanDefinitionRegistryPostProcessor 和 PriorityOrdered 的实现类. 所以会很快执行.

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

    public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {List<BeanDefinitionHolder> configCandidates = new ArrayList<>();

        // 获取注册表中注册的类名. 
        String[] candidateNames = registry.getBeanDefinitionNames();

        for (String beanName : candidateNames) {
            // 获得 BeanDefinition
            BeanDefinition beanDef = registry.getBeanDefinition(beanName);
            // 防止重复执行
            if (ConfigurationClassUtils.isFullConfigurationClass(beanDef) ||
                    ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) {if (logger.isDebugEnabled()) {logger.debug("Bean definition has already been processed as a configuration class:" + beanDef);
                }
            }
            // 必须是 @Configuration 或者 @Bean 注解的 满足条件的只有一个 Spring 的入口类
             else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
            }
        }

        // Return immediately if no @Configuration classes were found
        // 到这里 就
        if (configCandidates.isEmpty()) {return;}

        // Sort by previously determined @Order value, if applicable
        // 排序
        configCandidates.sort((bd1, bd2) -> {int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
            int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
            return Integer.compare(i1, i2);
        });

        // Detect any custom bean name generation strategy supplied through the enclosing application context
        SingletonBeanRegistry sbr = null;
        if (registry instanceof SingletonBeanRegistry) {sbr = (SingletonBeanRegistry) registry;
            if (!this.localBeanNameGeneratorSet) {BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR);
                if (generator != null) {
                    this.componentScanBeanNameGenerator = generator;
                    this.importBeanNameGenerator = generator;
                }
            }
        }

        if (this.environment == null) {this.environment = new StandardEnvironment();
        }

        // Parse each @Configuration class
        //@Configuration 注解的解析器 
        //registry 是 org.springframework.beans.factory.support.DefaultListableBeanFactory
        //resourceLoader 是 org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext
        //componentScanBeanNameGenerator 是 AnnotationBeanNameGenerator. 给 bean 取名字的
        // 这个构造器里会 new ComponentScanAnnotationParser(environment, resourceLoader, componentScanBeanNameGenerator, registry); 看名字就可以直到这是 @ComponentScan 的解析器
        ConfigurationClassParser parser = new ConfigurationClassParser(
                this.metadataReaderFactory, this.problemReporter, this.environment,
                this.resourceLoader, this.componentScanBeanNameGenerator, registry);

        Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
        Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
        // 循环 pase. 以为在 parse 的时候 也会伴随新的 BeanDefinition 的注册. 这些新注册的可能也是需要 parse 的
        do {parser.parse(candidates);
            parser.validate();
            // 当执行解析之后 这里获得了所有的解析完成的集合
            Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
            configClasses.removeAll(alreadyParsed);

            // Read the model and create bean definitions based on its content
            if (this.reader == null) {
                this.reader = new ConfigurationClassBeanDefinitionReader(
                        registry, this.sourceExtractor, this.resourceLoader, this.environment,
                        this.importBeanNameGenerator, parser.getImportRegistry());
            }
            // 通过阅读器注册到 BeanFactory 中 () 例外是 @ImportResource 注解  他会调用响应的阅读器. 继续注入到 beanFactory
            this.reader.loadBeanDefinitions(configClasses);
            // 标记已经解析完成的
            alreadyParsed.addAll(configClasses);
            // 解析候选列表清除
            candidates.clear();
            // 如果注册标的数量 大于 刚开始解析之前的数量  说明是解析 Configuration 类的时候有注册的  所以要继续 parse
            if (registry.getBeanDefinitionCount() > candidateNames.length) {
                // BeanFactory 中所有的
                String[] newCandidateNames = registry.getBeanDefinitionNames();
                // 老的
                Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
                // 已经 parse 的
                Set<String> alreadyParsedClasses = new HashSet<>();
                for (ConfigurationClass configurationClass : alreadyParsed) {
                    // 合并 alreadyParsed 和 alreadyParsedClasses
                    alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
                }
                for (String candidateName : newCandidateNames) {
                    // 老的中不包含
                    if (!oldCandidateNames.contains(candidateName)) {BeanDefinition bd = registry.getBeanDefinition(candidateName);
                        // 已经 parse 的要排除掉
                        if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
                                !alreadyParsedClasses.contains(bd.getBeanClassName())) {
                                    // 这里添加的就是 parse 阶段新添加的.
                            candidates.add(new BeanDefinitionHolder(bd, candidateName));
                        }
                    }
                }
                candidateNames = newCandidateNames;
            }
        }
        // 继续 parse
        while (!candidates.isEmpty());

        // Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
        if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
        }

        if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
            // Clear cache in externally provided MetadataReaderFactory; this is a no-op
            // for a shared cache since it'll be cleared by the ApplicationContext.
            ((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();}
    }

ConfigurationClassParser#parse(candidates) candidates(spring 项目的入口类) 也就是 @SpringBootApplication 标记了这个注解的类

// 构造器
    public ConfigurationClassParser(MetadataReaderFactory metadataReaderFactory,
            ProblemReporter problemReporter, Environment environment, ResourceLoader resourceLoader,
            BeanNameGenerator componentScanBeanNameGenerator, BeanDefinitionRegistry registry) {

        this.metadataReaderFactory = metadataReaderFactory;
        this.problemReporter = problemReporter;
        this.environment = environment;
        this.resourceLoader = resourceLoader;
        this.registry = registry;
        // 这里
        this.componentScanParser = new ComponentScanAnnotationParser(environment, resourceLoader, componentScanBeanNameGenerator, registry);
        // 这里
        this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
    }

    public void parse(Set<BeanDefinitionHolder> configCandidates) {for (BeanDefinitionHolder holder : configCandidates) {BeanDefinition bd = holder.getBeanDefinition();
            try {if (bd instanceof AnnotatedBeanDefinition) {parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());
                }
                else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) {parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName());
                }
                else {parse(bd.getBeanClassName(), holder.getBeanName());
                }
            }
            catch (BeanDefinitionStoreException ex) {throw ex;}
            catch (Throwable ex) {
                throw new BeanDefinitionStoreException("Failed to parse configuration class [" + bd.getBeanClassName() + "]", ex);
            }
        }
        // 延迟执行的 这里执行了
        this.deferredImportSelectorHandler.process();}

    protected final void parse(@Nullable String className, String beanName) throws IOException {Assert.notNull(className, "No bean class name for configuration class bean definition");
        MetadataReader reader = this.metadataReaderFactory.getMetadataReader(className);
        processConfigurationClass(new ConfigurationClass(reader, beanName));
    }

    protected final void parse(Class<?> clazz, String beanName) throws IOException {processConfigurationClass(new ConfigurationClass(clazz, beanName));
    }

    protected final void parse(AnnotationMetadata metadata, String beanName) throws IOException {processConfigurationClass(new ConfigurationClass(metadata, beanName));
    }


    protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {return;}

        ConfigurationClass existingClass = this.configurationClasses.get(configClass);
        if (existingClass != null) {if (configClass.isImported()) {if (existingClass.isImported()) {existingClass.mergeImportedBy(configClass);
                }
                // Otherwise ignore new imported config class; existing non-imported class overrides it.
                return;
            }
            else {
                // Explicit bean definition found, probably replacing an import.
                // Let's remove the old one and go with the new one.
                this.configurationClasses.remove(configClass);
                this.knownSuperclasses.values().removeIf(configClass::equals);
            }
        }

        // Recursively process the configuration class and its superclass hierarchy.
        SourceClass sourceClass = asSourceClass(configClass);
        do {sourceClass = doProcessConfigurationClass(configClass, sourceClass);
        }
        while (sourceClass != null);
        // 每当解析完成以后 就添加到这集合中 ConfigurationClassParser 的 configurationClasses 集合
        this.configurationClasses.put(configClass, configClass);
    }

    @Nullable
    protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
            throws IOException {

        // 优先解析标记了 @Component 注解的类 解析例如在 @Controller 里写的 @Bean 或者 @Configuration 嵌套的情况. 在入口类中写了一些逻辑的情况
        if (configClass.getMetadata().isAnnotated(Component.class.getName())) {// Recursively process any member (nested) classes first
            processMemberClasses(configClass, sourceClass);
        }

        // Process any @PropertySource annotations
        // 解析 @PropertySource 注解  例如这种情况
        //  @Configuration
        //@PropertySource("classpath:/com/myco/a.properties")
        //public class ConfigA { }
        //
        for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(sourceClass.getMetadata(), PropertySources.class,
                org.springframework.context.annotation.PropertySource.class)) {if (this.environment instanceof ConfigurableEnvironment) {processPropertySource(propertySource);
            }
            else {logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
                        "]. Reason: Environment must implement ConfigurableEnvironment");
            }
        }

        // Process any @ComponentScan annotations
        //sourceClass.getMetadata() 上的 @ComponentScan 注解的解析 兼容 ComponentScans 的形式
        Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
        if (!componentScans.isEmpty() &&
                !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
            // 遍历一个一个解析
            for (AnnotationAttributes componentScan : componentScans) {
                // The config class is annotated with @ComponentScan -> perform the scan immediately
                //case 1 
                Set<BeanDefinitionHolder> scannedBeanDefinitions =
                        this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
                // Check the set of scanned definitions for any further config classes and parse recursively if needed
                // 拿到了 ComponentScan 指定扫描包中所有的元注解为 @Component 的类
                for (BeanDefinitionHolder holder : scannedBeanDefinitions) {BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
                    if (bdCand == null) {bdCand = holder.getBeanDefinition();
                    }
                    if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
                        // 继续解析 这些类中 @Configuration 和 @Bean 的类
                        parse(bdCand.getBeanClassName(), holder.getBeanName());
                    }
                }
            }
        }

        // Process any @Import annotations
        // getImports(sourceClass) 这个方法是获取 @Import 注解导入的类, 平铺开 以 @SpringBootApplication 注解为例子  返回的 Set<SourceClass> 集合中包含
        //AutoConfigurationImportSelector.class 和 AutoConfigurationPackages.Registrar.class
        // processImports  case 3
        processImports(configClass, sourceClass, getImports(sourceClass), true);

        // Process any @ImportResource annotations
        // @ImportResource 注解的解析. 并将解析的类注册到 ConfigurationClass 类的 importedResources map 中
        AnnotationAttributes importResource =
                AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
        if (importResource != null) {String[] resources = importResource.getStringArray("locations");
            Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
            for (String resource : resources) {String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
                configClass.addImportedResource(resolvedResource, readerClass);
            }
        }

        // Process individual @Bean methods
        // @Bean 注解的解析 注册 ConfigurationClass 类的 beanMethods SET 中
        Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
        for (MethodMetadata methodMetadata : beanMethods) {configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
        }

        // Process default methods on interfaces
        processInterfaces(configClass, sourceClass);

        // Process superclass, if any
        if (sourceClass.getMetadata().hasSuperClass()) {String superclass = sourceClass.getMetadata().getSuperClassName();
            if (superclass != null && !superclass.startsWith("java") &&
                    !this.knownSuperclasses.containsKey(superclass)) {this.knownSuperclasses.put(superclass, configClass);
                // Superclass found, return its annotation metadata and recurse
                return sourceClass.getSuperClass();}
        }

        // No superclass -> processing is complete
        return null;
    }

ConfigurationClassParser#parse(candidates) 内部执行的方法就是 doProcessConfigurationClass()

case:1 ComponentScanAnnotationParser#parse() 方法

public Set<BeanDefinitionHolder> parse(AnnotationAttributes componentScan, final String declaringClass) {
        //case 2 
        // 这个扫描器很熟悉了 componentScan.getBoolean("useDefaultFilters") = true
        ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this.registry,
                componentScan.getBoolean("useDefaultFilters"), this.environment, this.resourceLoader);

        Class<? extends BeanNameGenerator> generatorClass = componentScan.getClass("nameGenerator");
        boolean useInheritedGenerator = (BeanNameGenerator.class == generatorClass);
        scanner.setBeanNameGenerator(useInheritedGenerator ? this.beanNameGenerator :
                BeanUtils.instantiateClass(generatorClass));

        ScopedProxyMode scopedProxyMode = componentScan.getEnum("scopedProxy");
        if (scopedProxyMode != ScopedProxyMode.DEFAULT) {scanner.setScopedProxyMode(scopedProxyMode);
        }
        else {Class<? extends ScopeMetadataResolver> resolverClass = componentScan.getClass("scopeResolver");
            scanner.setScopeMetadataResolver(BeanUtils.instantiateClass(resolverClass));
        }

        scanner.setResourcePattern(componentScan.getString("resourcePattern"));

        for (AnnotationAttributes filter : componentScan.getAnnotationArray("includeFilters")) {for (TypeFilter typeFilter : typeFiltersFor(filter)) {scanner.addIncludeFilter(typeFilter);
            }
        }
        for (AnnotationAttributes filter : componentScan.getAnnotationArray("excludeFilters")) {for (TypeFilter typeFilter : typeFiltersFor(filter)) {scanner.addExcludeFilter(typeFilter);
            }
        }

        boolean lazyInit = componentScan.getBoolean("lazyInit");
        if (lazyInit) {scanner.getBeanDefinitionDefaults().setLazyInit(true);
        }

        Set<String> basePackages = new LinkedHashSet<>();
        String[] basePackagesArray = componentScan.getStringArray("basePackages");
        for (String pkg : basePackagesArray) {String[] tokenized = StringUtils.tokenizeToStringArray(this.environment.resolvePlaceholders(pkg),
                    ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
            Collections.addAll(basePackages, tokenized);
        }
        for (Class<?> clazz : componentScan.getClassArray("basePackageClasses")) {basePackages.add(ClassUtils.getPackageName(clazz));
        }
        //basePackages 和 basePackageClasses 的解析是去并集的.
        // basePackages 和 basePackageClasses 都设置过. 那么就用 declaringClass 的包目录. 
        //declaringClass 这个类就是我们 spring 的入口类, 可以理解为入口类放在哪个包. 扫描哪个包下的所有类.
        if (basePackages.isEmpty()) {basePackages.add(ClassUtils.getPackageName(declaringClass));
        }

        scanner.addExcludeFilter(new AbstractTypeHierarchyTraversingFilter(false, false) {
            @Override
            protected boolean matchClassName(String className) {return declaringClass.equals(className);
            }
        });
        // 扫描逻辑. 因为是注解驱动的. 所以扫描 basePackages 包下所有元注解为 @Component 的. 
        // 元注解的意思就是 注解上的注解. 我们熟知的 Controller 的元注解就是 @Component. 自己去看吧
        // 读取类信息是通过 ASM 做的. ASM 我是实在看不懂了.
        return scanner.doScan(StringUtils.toStringArray(basePackages));
    }

ClassPathBeanDefinitionScanner 类

ClassPathBeanDefinitionScanner#doScan 在扫描时 是扫描所有的 basePackages 下所有的.Class 文件. 不要那些类和留下那些类. 是通过过滤器实现的

includeFilters 是留下类的过滤器

  1. new AnnotationTypeFilter(Component.class)
  2. new AnnotationTypeFilter(((Class<? extends Annotation>) ClassUtils.forName(“javax.annotation.ManagedBean”, cl)), false)
  3. new AnnotationTypeFilter(((Class<? extends Annotation>) ClassUtils.forName(“javax.inject.Named”, cl)), false)

excludeFilters 是不要类过滤器: 是 componentScan 指定的 “@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),

    @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })``

TypeExcludeFilter 和 AutoConfigurationExcludeFilter 过滤器. 大体是 @Configuration MATE-INF/spring.factories 文件中 EnableAutoConfiguration 类型的类 排除


    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);
    }
    // ClassPathScanningCandidateComponentProvider 是 ClassPathBeanDefinitionScanner 父类 包含的过滤器. 留下的类
    @SuppressWarnings("unchecked")
    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.}
    }

经过扫描 最后留下的类基本就这

  • {@link Component @Component}, {@link Repository @Repository},
  • {@link Service @Service}, and {@link Controller @Controller}

processImports(configClass, sourceClass, getImports(sourceClass), true)

以入口类为例子:

configClass 和 sourceClass 值都是 spring 的入口类

importCandidates 指的是 入口类上 @import() 注解导入类的集合

checkForCircularImports 检查循环导入

  1. 先执行注册延迟导入相关 DeferredImportSelector
  2. 再执行 ImportSelector#selectImports 返回是一些类的名字. 继续 processImports() 这种方式是 导入其他自动装配类的时候使用的
  3. ImportBeanDefinitionRegistrar 注册实现了 ImportBeanDefinitionRegistrar 接口的类到 importBeanDefinitionRegistrars 到 Map 注意这里并没有执行
  4. 以上情况都不是 就执行 @Configuration 标注的类本身 最终状态. 解析 @Bean 的情况
private void processImports(ConfigurationClass configClass, SourceClass currentSourceClass,
            Collection<SourceClass> importCandidates, boolean checkForCircularImports) {if (importCandidates.isEmpty()) {return;}

        if (checkForCircularImports && isChainedImportOnStack(configClass)) {this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
        }
        else {
            // 解决循环导入的
            this.importStack.push(configClass);
            try {for (SourceClass candidate : importCandidates) {if (candidate.isAssignable(ImportSelector.class)) {
                        // Candidate class is an ImportSelector -> delegate to it to determine imports
                        Class<?> candidateClass = candidate.loadClass();
                        ImportSelector selector = BeanUtils.instantiateClass(candidateClass, ImportSelector.class);
                        ParserStrategyUtils.invokeAwareMethods(selector, this.environment, this.resourceLoader, this.registry);
                        if (selector instanceof DeferredImportSelector) {this.deferredImportSelectorHandler.handle(configClass, (DeferredImportSelector) selector);
                        }
                        else {String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());
                            Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames);
                            processImports(configClass, currentSourceClass, importSourceClasses, false);
                        }
                    }
                    else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) {
                        // Candidate class is an ImportBeanDefinitionRegistrar ->
                        // delegate to it to register additional bean definitions
                        Class<?> candidateClass = candidate.loadClass();
                        // 初始化
                        ImportBeanDefinitionRegistrar registrar =
                                BeanUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class);
                                // setAware
                        ParserStrategyUtils.invokeAwareMethods(registrar, this.environment, this.resourceLoader, this.registry);
                                // 注册
                        configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata());
                    }
                    else {
                        // Candidate class not an ImportSelector or ImportBeanDefinitionRegistrar ->
                        // process it as an @Configuration class
                        this.importStack.registerImport(currentSourceClass.getMetadata(), candidate.getMetadata().getClassName());
                        processConfigurationClass(candidate.asConfigClass(configClass));
                    }
                }
            }
            catch (BeanDefinitionStoreException ex) {throw ex;}
            catch (Throwable ex) {
                throw new BeanDefinitionStoreException(
                        "Failed to process import candidates for configuration class [" +
                        configClass.getMetadata().getClassName() + "]", ex);
            }
            finally {this.importStack.pop();
            }
        }
    }

正文完
 0