作用:
1)@Import:源码的正文中曾经表明,它的性能等于@bean,<import/>。能够引入一个类(这个类能够是一般类,也能够是@Configuraion/Component润饰的类),并且退出到Spring容器中,程序中能够间接@autowired注入
2)前两种形式退出容器时,bean id为全限定类名,第三种形式能够自定义id
第三种形式的长处在于能够自定义创立bean的过程。
1.间接引入对应类的Class对象,
//MyImportSelector,MyImportBeanDefinitionRegistrar别离实现了两个接口@Import({TestA.class,TestB.class,MyImportSelector.class,MyImportBeanDefinitionRegistrar.class})public class SpringConfig { }public class TestA { public TestA() { System.out.println("执行testA的无参构造方法"); } public void funTestA() { System.out.println("执行testA中的funTestA办法"); }} public class TestB { public TestB() { System.out.println("执行TestB的无参构造方法"); } public void funTestB() { System.out.println("执行TestB中的funTestB办法"); }}
2.实现ImportSelector接口
1)能够返回空数组,然而不能返回null,否则会报空指针异样
/** * 实现ImportSelector,重写办法selectImports,返回须要引入的类,并创立实例,退出spring容器 */public class MyImportSelector implements ImportSelector { public MyImportSelector() { System.out.println("MyImportSelector构造方法"); } @Override public String[] selectImports(AnnotationMetadata annotationMetadata) { return new String[]{"com.lagou.edu.testimport.TestC"}; } }
3.实现ImportBeanDefinitionRegistrar接口
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar { public MyImportBeanDefinitionRegistrar() { System.out.println("执行MyImportBeanDefinitionRegistrar的构造方法"); } @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { //指定要注册的bean信息 RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(TestD.class); //注册bean,并指定bean的id registry.registerBeanDefinition("testD", rootBeanDefinition); }}
测试案例
@Testpublic void test3() { AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class); TestA testA =(TestA) ac.getBean("com.lagou.edu.testimport.TestA"); testA.funTestA(); TestB testB =(TestB) ac.getBean("com.lagou.edu.testimport.TestB"); testB.funTestB(); TestC testC =(TestC) ac.getBean("com.lagou.edu.testimport.TestC"); testC.funTestC(); //注册bean时指定了bean的id, TestD testD =(TestD) ac.getBean("testD"); testD.funTestD();}