1. 编写实现ImportSelector的类
/** * @author 70KG * @Title: SelectImportBean * @Description: * @date 2018/7/22下午4:59 * @From www.nmyswls.com */ public class SelectImportBean implements ImportSelector { @Override public String[] selectImports(AnnotationMetadata annotationMetadata) { return new String[]{"com.nmys.story.springCore.springioc.importBean.Fish","com.nmys.story.springCore.springioc.importBean.Pig"}; } }
2. 编写配置类
/** * @author 70KG * @Title: Config * @Description: * @date 2018/7/22下午4:41 * @From www.nmyswls.com */ @Configuration // 会自动向容器中加入实例化后的bean,默认的id是bean的全类名 @Import(value = {Dog.class, Cat.class, SelectImportBean.class}) public class ImportBeanConfig { }
3. 测试类
public class Test01 { @Test public void test() { // IOC容器创建(容器类似一个Map) AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ImportBeanConfig.class); System.out.println("IOC容器初始化完成。。。。。"); // 从容器中获取所有的bean的ID String[] definitionNames = ac.getBeanDefinitionNames(); for (String name : definitionNames) { System.out.println("------->" + name); } } }
4. 测试结果
IOC容器初始化完成。。。。。 ------->org.springframework.context.annotation.internalConfigurationAnnotationProcessor ------->org.springframework.context.annotation.internalAutowiredAnnotationProcessor ------->org.springframework.context.annotation.internalRequiredAnnotationProcessor ------->org.springframework.context.annotation.internalCommonAnnotationProcessor ------->org.springframework.context.event.internalEventListenerProcessor ------->org.springframework.context.event.internalEventListenerFactory ------->importBeanConfig ------->com.nmys.story.springCore.springioc.importBean.Dog ------->com.nmys.story.springCore.springioc.importBean.Cat ------->com.nmys.story.springCore.springioc.importBean.Fish ------->com.nmys.story.springCore.springioc.importBean.Pig
5. ImportSelector用于向容器中导入指定的类。
原文地址:https://www.cnblogs.com/zhangjianbing/p/10114148.html
时间: 2024-11-01 11:05:05