美文网首页
Spring Boot中实现多个类同时自动装配

Spring Boot中实现多个类同时自动装配

作者: 蓉漂里的小白 | 来源:发表于2021-02-03 15:31 被阅读0次

    @Import注解是将指定的Bean加入到IOC容器之中进行管理,ImportSelector接口只有一个selectImports方法,该方法将返回一个数组,也就是类实例名称,@Import
    注解将会把selectImports返回的所有Bean全部加入到IOC容器中进行管理。

    1:创建二个需要被注入容器中的bean:TestService1, TestService2

    public class TestService1 {
        public String outPut(){
            return "i am service1";
        }
    }
    
    public class TestService2 {
    
        public String outPut(){
            return "i am service2";
        }
    }
    

    2: 创建一个class实现importSelector接口,并将第一步中创建的类(TestService1, TestService2)加入到selectImports方法的数组中

    public class TestServiceImport implements ImportSelector {
        @Override
        public String[] selectImports(AnnotationMetadata annotationMetadata) {
            return new String[]{TestService1.class.getName(), TestService2.class.getName()};
        }
    }
    

    3:创建一个Enable的注解,使用@import注解将上一步创建的importSelector类进行导入

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Inherited
    @Documented
    @Import(TestServiceImport.class)
    public @interface EnableTestService {
    }
    

    4:在方法,类上直接使用@EnableDefineService注解既可完成TestService到spring ioc容器的注入

    @RestController
    @RequestMapping("jmx")
    public class JmxController {
    
        @Autowired
        private TestService1 testService1;
    
        @Autowired
        private TestService2 testService2;
    
        @GetMapping("/testService")
        public void setTestService(){
            System.out.println(this.testService1.outPut());
            System.out.println(this.testService2.outPut());
        }
    
    @EnableTestService
    @SpringBootApplication
    public class JMXTestApplication {
        public static void main(String[] args){
              SpringApplication.run(JMXTestApplication.class, args);
        }
    

    5:测试效果

    启动程序,然后再浏览器输入请求路径http://localhost:8888/jmx/testService
    可以看到控制台输出了testService的打印,说明完成了通过一个自定义的注解实现多个类同时注入到Spring ioc中

    image.png

    相关文章

      网友评论

          本文标题:Spring Boot中实现多个类同时自动装配

          本文链接:https://www.haomeiwen.com/subject/bszptltx.html