Spring Boot自动注入原理
2021-02-18 15:18
标签:ESS data which 开启 ring reg author The lang 使用注解 Spring Boot通过 实现bean动态注入可以通过两种方式。 Spring Boot自动注入原理 标签:ESS data which 开启 ring reg author The lang 原文地址:https://www.cnblogs.com/kancy/p/12689656.html启用自动注入
@EnableAutoConfiguration
开启自动注入功能。@EnableAutoConfiguration
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
// ignore...
}
@AutoConfigurationPackage
@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {
}
AutoConfigurationImportSelector.class
和AutoConfigurationPackages.Registrar.class
这两个类配合使用,实现动态注入。
其中,类AutoConfigurationImportSelector.class
会加载spring-autoconfigure-metadata.properties
,并且进行过滤筛选,将需要动态注入的类全路径交给AutoConfigurationPackages.Registrar.class
进行初始化注入。动态注入SpingBean
方案一:实现ImportSelector接口
/* @author Chris Beams
* @since 3.1
* @see DeferredImportSelector
* @see Import
* @see ImportBeanDefinitionRegistrar
* @see Configuration
*/
public interface ImportSelector {
/**
* Select and return the names of which class(es) should be imported based on
* the {@link AnnotationMetadata} of the importing @{@link Configuration} class.
*/
String[] selectImports(AnnotationMetadata importingClassMetadata);
}
方案二:实现ImportSelector接口
/* @author Chris Beams
* @since 3.1
* @see Import
* @see ImportSelector
* @see Configuration
*/
public interface ImportBeanDefinitionRegistrar {
/**
* Register bean definitions as necessary based on the given annotation metadata of
* the importing {@code @Configuration} class.
* @param importingClassMetadata annotation metadata of the importing class
* @param registry current bean definition registry
*/
void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry);
}