启用自动注入
使用注解@EnableAutoConfiguration
开启自动注入功能。
@EnableAutoConfiguration
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
// ignore...
}
@AutoConfigurationPackage
@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {
}
Spring Boot通过AutoConfigurationImportSelector.class
和AutoConfigurationPackages.Registrar.class
这两个类配合使用,实现动态注入。
其中,类AutoConfigurationImportSelector.class
会加载spring-autoconfigure-metadata.properties
,并且进行过滤筛选,将需要动态注入的类全路径交给AutoConfigurationPackages.Registrar.class
进行初始化注入。
动态注入SpingBean
实现bean动态注入可以通过两种方式。
方案一:实现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);
}
原文地址:https://www.cnblogs.com/kancy/p/12689656.html
时间: 2024-10-16 08:07:46