转:https://blog.csdn.net/lizhiqiang1217/article/details/89949542
1、MainConfig2
@Configuration
//ImportSelector:返回需要导入的组件的全类名数组;
@Import(MyImportSelector.class)
public class MainConfig2 {
}
2、自定义需要导入的组件MyImportSelector 。实现ImportSelector 接口
//自定义逻辑返回需要导入的组件
public class MyImportSelector implements ImportSelector {
//返回值,就是到导入到容器中的组件全类名
//AnnotationMetadata:当前标注@Import注解的类的所有注解信息
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
// TODO Auto-generated method stub
//方法不要返回null值
return new String[]{"com.atguigu.bean.Color","com.atguigu.bean.Red"};
}
}
3、测试
@Test
public void testImportSelector(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig2.class);
String[] definitionNames = applicationContext.getBeanDefinitionNames();
for (String name : definitionNames) {
System.out.println(name);
}
}