当前位置: 首页 > 后端技术 > Java

@Import

时间:2023-04-01 22:32:40 Java

功能的使用:1)@Import:在源码注释中已经说明其功能等同于@bean,。可以引入一个类(这个类可以是普通类,也可以是@Configuraion/Component修饰的类),添加到Spring容器中,@autowired可以直接注入到程序中2)添加前两个方法时给容器,beanid为全限定类名,第三种方法可以自定义id第三种方法的好处是可以自定义创建bean的过程。1.直接引入对应类的Class对象,//MyImportSelector,MyImportBeanDefinitionRegistrar分别实现两个接口@Import({TestA.class,TestB.class,MyImportSelector.class,MyImportBeanDefinitionRegistrar.class})publicclassSpringConfig{}publicclassTestA{publicTestA(){System.out.println("执行testA的无参构造方法");}publicvoidfunTestA(){System.out.println("执行testA中的funTestA方法");}}publicclassTestB{publicTestB(){System.out.println("执行TestB的无参构造方法");}publicvoidfunTestB(){System.out.println("执行TestB中的funTestB方法");}}2.实现ImportSelector接口1)可以返回空数组,但不能返回null,否则会报空指针异常/***实现ImportSelector,重写方法selectImports,返回需要导入的类,创建实例,加入spring容器*/publicclassMyImportSelectorimplementsImportSelector{publicMyImportSelector(){System.out.println("MyImportSelector构造方法");}@OverridepublicString[]selectImports(AnnotationMetadataannotationMetadata){returnnewString[]{"com.lagou.edu.testimport.Testc“};}}}}3。实现importBeanDefInitionRegistrar接口公共类MyimportBeanDefinegregrregistrar实现ImportBeanDefinienregistrar{publicmyimportbeandefinitionRegistrar(){//指定要注册的bean信息RootBeanDefinitionrootBeanDefinition=newRootBeanDefinition(TestD.class);//注册bean并指定bean的idregistry.registerBeanDefinition("testD",rootBeanDefinition);}}测试用例@Testpublicvoidtest3(){AnnotationConfigApplicationContextac=newAnnotationConfigApplicationContext(SpringConfig.class);TestAtestA=(TestA)ac.getBean("com.lagou.edu.testimport.TestA");testA.funTestA();TestBtestB=(TestB)ac.getBean("com.lagou.edu.testimport.TestB");testB.funTestB();TestCtestC=(TestC)ac.getBean("com.lagou.edu.testimport.TestC");testC.funTestC();//注册bean时指定bean的id,TestDtestD=(TestD)ac.getBean("testD");testD.funTestD();}