1.@Import注解
- 用于注入指定的类,导入组件id默认是组件的全类名。
- 只能作用于类上。
- 属性:value = {xx.class,xx.class} 说明:xx.class为要导入到容器中的组件
属性value中class分为三类:
1)普通类直接注入
2)实现ImportSelector接口的类
3)实现ImportBeanDefinitionRegistrar接口的类
说明:
- ImportSelector:返回需要导入的组件的全类名数组;
- ImportBeanDefinitionRegistrar:手动注册bean到容器中;
2.@Import注入原理
import类注入是通过org.springframework.context.annotation.ConfigurationClassPostProcessor后置处理器来注入的。
核心方法:postProcessBeanDefinitionRegistry
/**
* Derive further bean definitions from the configuration classes in the registry.
*/
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
int registryId = System.identityHashCode(registry);
//判断后置处理器在registriesPostProcessed和factoriesPostProcessed中有没有被调用过
if (this.registriesPostProcessed.contains(registryId)) {
throw new IllegalStateException(
"postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
}
if (this.factoriesPostProcessed.contains(registryId)) {
throw new IllegalStateException(
"postProcessBeanFactory already called on this post-processor against " + registry);
}
//调用前保存registryId,防止被重复调用
this.registriesPostProcessed.add(registryId);
//注入标有@configuration的对象
processConfigBeanDefinitions(registry);
}
/** 构建和校验标有@configuration注解的对象
* Build and validate a configuration model based on the registry of
* {@link Configuration} classes.
*/
public void processConfigBeanDefinitions(BeanDefinitionRegistry re