赞
踩
SpringBoot的自动装配是SpringBoot的核心,而SpringBoot的启动类上的@SpringBootApplication注解中包括@SpringBootConfiguration、@EnableAutoConfiguration和@ComponentScan三个注解,其中@EnableAutoConfiguration就是自动装配的核心注解。
- @Target({ElementType.TYPE})
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- @Inherited
- @SpringBootConfiguration
- //自动装配的核心注解
- @EnableAutoConfiguration
- @ComponentScan(
- excludeFilters = {@Filter(
- type = FilterType.CUSTOM,
- classes = {TypeExcludeFilter.class}
- ), @Filter(
- type = FilterType.CUSTOM,
- classes = {AutoConfigurationExcludeFilter.class}
- )}
- )
- public @interface SpringBootApplication {
- }
对@EnableAutoConfiguration进行跟踪,@Import({AutoConfigurationImportSelector.class})就是负责自动装配。
- @Target({ElementType.TYPE})
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- @Inherited
- @AutoConfigurationPackage
- @Import({AutoConfigurationImportSelector.class})
- public @interface EnableAutoConfiguration {
- String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
-
- Class<?>[] exclude() default {};
-
- String[] excludeName() default {};
- }
跟踪AutoConfigurationImportSelector.class,其中有个getAutoConfigurationEntry方法,用于自动获取配置了类信息。
- 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);
- }
- }
其中getCandidateConfigurations方法用于获取候选配置
- protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
- List<String> configurations = ImportCandidates.load(AutoConfiguration.class, this.getBeanClassLoader()).getCandidates();
- Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports. If you are using a custom packaging, make sure that file is correct.");
- return configurations;
- }
其中的ImportCandidates.load方法解析出配置文件的路径"META-INF/spring/%s.imports",也就是spring-boot-autoconfigure包下的META-INF下的spring中的org.springframework.boot.autoconfigure.AutoConfiguration.imports文件
文件中就包括了自动加载的类,在具体的装配时,会进行条件判断,符合了才会自动装配,也就是判断项目中是否真的引入了依赖。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。