SpringBoot自动装配

  1. SpringBoot入口
    SpringBoot入口
  2. springboot启动时,启动类注解中开启自动装配。
    其中有三个主要注解:
  • @ComponentScan:扫描包路径,会把指定路径下带有指定注解的类自动装配到bean容器里。@Service,@Controller,@Component,@Repository等
  • @SpringBootConfiguration:标识该类是配置类,用于扩展
  • @EnableAutoConfiguration:最核心注解,开启自动装配。包括@AutoConfigurationPackage 和 @Import({AutoConfigurationImportSelector.class})
    开启自动装配中,导入自动装配选择器AutoConfigurationImportSelector。
    SpringBoot核心注解
    SpringBoot自动装配核心注解
  1. AutoConfigurationImportSelector 选择器 getCandidateConfigurations方法为了获取到哪些配置属性
// 获取自动装配实体
protected AutoConfigurationImportSelector.AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {
        if (!this.isEnabled(annotationMetadata)) {
            return EMPTY_ENTRY;
        } else {
            AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
            List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
            configurations = this.removeDuplicates(configurations);
            Set<String> exclusions = this.getExclusions(annotationMetadata, attributes);
            this.checkExcludedClasses(configurations, exclusions);
            configurations.removeAll(exclusions);
            configurations = this.getConfigurationClassFilter().filter(configurations);
            this.fireAutoConfigurationImportEvents(configurations, exclusions);
            return new AutoConfigurationImportSelector.AutoConfigurationEntry(configurations, exclusions);
        }
 }
// 获取候选的配置信息
 protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
		// 调用工具类 获取所有加载配置类并将其放置容器中
        List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
        Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.");
        return configurations;
}
  1. 扫描所有jar包下面的MET-INF/spring.properties文件的url内容组成配置文件的格式,再把这些配置信息中key = EnableAutoConfiguration的配置信息加载到容器当中
 protected Class<?> getSpringFactoriesLoaderFactoryClass() {
        return EnableAutoConfiguration.class;
 }
// 获取所有加载配置类的名字
 public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
        ClassLoader classLoaderToUse = classLoader;
        if (classLoader == null) {
            classLoaderToUse = SpringFactoriesLoader.class.getClassLoader();
        }

        String factoryTypeName = factoryType.getName();
        return (List)loadSpringFactories(classLoaderToUse).getOrDefault(factoryTypeName, Collections.emptyList());
 }
// 获取所有配置 封装到map中
private static Map<String, List<String>> loadSpringFactories(ClassLoader classLoader) {
        Map<String, List<String>> result = (Map)cache.get(classLoader);
        if (result != null) {
            return result;
        } else {
            HashMap result = new HashMap();

            try {
                Enumeration urls = classLoader.getResources("META-INF/spring.factories");
				// 遍历urls 将url封装成properties供我们使用
                while(urls.hasMoreElements()) {
                    URL url = (URL)urls.nextElement();
                    UrlResource resource = new UrlResource(url);
                    Properties properties = PropertiesLoaderUtils.loadProperties(resource);
                    Iterator var6 = properties.entrySet().iterator();

                    while(var6.hasNext()) {
                        Entry<?, ?> entry = (Entry)var6.next();
                        String factoryTypeName = ((String)entry.getKey()).trim();
                        String[] factoryImplementationNames = StringUtils.commaDelimitedListToStringArray((String)entry.getValue());
                        String[] var10 = factoryImplementationNames;
                        int var11 = factoryImplementationNames.length;

                        for(int var12 = 0; var12 < var11; ++var12) {
                            String factoryImplementationName = var10[var12];
                            ((List)result.computeIfAbsent(factoryTypeName, (key) -> {
                                return new ArrayList();
                            })).add(factoryImplementationName.trim());
                        }
                    }
                }

                result.replaceAll((factoryType, implementations) -> {
                    return (List)implementations.stream().distinct().collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
                });
                cache.put(classLoader, result);
                return result;
            } catch (IOException var14) {
                throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var14);
            }
        }
    }

可以看到,是读取resource目录下的spring.factories去获取自动装配的数据

  1. spring容器再利用@ConditionalXXX注解判断这些自动配置类是否符合条件,符合条件的话,加载配置信息
    常用的Condition条件注解

版权声明:本文为weixin_45472766原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。