@Import 注解 快速的导入一个组件到容器中,组件id默认是全类名
一、使用@Import
假设我们要导入一个User类:
public class User {
}
配置类里:
@Configuration //告诉spring这是个配置类
@ComponentScan(value = "com.spring")
@Import(User.class) //快速导入User对象到ioc容器中
public class SpringConfig {
@Bean
public Person person01(){
System.out.println("person01..被创建放入ioc容器...");
return new Person("小米","22");
}
@Bean
public Person person02(){
System.out.println("person02..被创建放入ioc容器...");
return new Person("华为","20");
}
}
main方法测试:
二、使用ImportSelector——自定义逻辑导入组件
创建2个需要导入的类:
public class Cat {
}
public class Dog {
}
配置类:
@Configuration //告诉spring这是个配置类
@ComponentScan(value = "com.spring")
@Import({User.class,MyImportSelector.class}) //自定义导入逻辑
public class SpringConfig {
@Bean
public Person person01() {
System.out.println("person01..被创建放入ioc容器...");
return new Person("小米", "22");
}
@Bean
public Person person02() {
System.out.println("person02..被创建放入ioc容器...");
return new Person("华为", "20");
}
}
自定义导入逻辑:
public class MyImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
return new String[]{"com.spring.bean.Dog","com.spring.bean.Cat"};
}
}
main方法测试:
三、使用ImportBeanDefinitionRegistrar
手动注册
@Configuration //告诉spring这是个配置类
@ComponentScan(value = "com.spring")
@Import({User.class,MyImportBeanDefinitionRegistrar.class})
public class SpringConfig {
@Bean
public Person person01() {
System.out.println("person01..被创建放入ioc容器...");
return new Person("小米", "22");
}
@Bean
public Person person02() {
System.out.println("person02..被创建放入ioc容器...");
return new Person("华为", "20");
}
}
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
boolean b1 = registry.containsBeanDefinition("person01");
boolean b2 = registry.containsBeanDefinition("person02");
//如果容器中包含person01和person02 就注册一个Dog对象
if (b1 && b2){
RootBeanDefinition beanDefinition = new RootBeanDefinition(Dog.class);
//指定bean id名称
registry.registerBeanDefinition("is_name_Dog",beanDefinition);
}
}
}
main方法测试: