如何进行自动装配?
完成Spring Boot约定的组件自动装配需要包含三个因素:
激活@EnableAutoConfiguration注解(全流程管理)
配置/META-INF/spring.factories(约定,是否将组件下某个class加入自动装配管理)
实现xxxAutoConfiguration组件配置类(符合什么条件才加入自动装配)
整体流程是@EnableAutoConfiguration中实现类扫描“classpath下即pom依赖”中所有包含/META-INF/spring.factories的包,并根据xxxAutoConfiguration和/META-INF/spring-autoconfigure-metadata.properties中的条件判断来决定是否进行自动装配。
SpringBootApplication是一组注解的组合,其中包含@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 {}
而根据@Enable模块驱动设计模式(即Import的类被@Configuration注解或实现ImportSelector接口,可实现注入)@EnableAutoConfiguration必然Import了“实现ImportSelector接口的实现类”,并实现其SelectImport方法。
// 1. Import了AutoConfigurationImportSelector类
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
}
//2. 实现了DeferredImportSelector接口,并重写selectImports方法
public class AutoConfigurationImportSelector
implements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware,
BeanFactoryAware, EnvironmentAware, Ordered {
}
//3. 继承ImportSelector接口
public interface DeferredImportSelector extends ImportSelector {}
整体流程:
获取自动加载配置的元数据:主要是获取classpath下所有META-INF/spring-autoconfigure-metadata。properties中的配置信息,文件里面配置的作用等同于在xxxAutoConfiguration上面的@ConditionalOnClass等注解,这么做的好处就是参考官网说明。(Spring Boot uses an annotation processor to collect the conditions on auto-configurations in a metadata file (META-INF/spring-autoconfigure-metadata.properties). If that file is present, it is used to eagerly filter auto-configurations that do not match, which will improve startup time.)
网友评论