zoukankan      html  css  js  c++  java
  • ImportSelector介绍

    参考博客:https://blog.csdn.net/elim168/article/details/88131614

    @Configuration标注的Class上可以使用@Import引入其它的配置类,其实它还可以引入org.springframework.context.annotation.ImportSelector实现类。

    ImportSelector接口只定义了一个selectImports(),用于指定需要注册为bean的Class名称。

    当在@Configuration标注的Class上使用@Import引入了一个ImportSelector实现类后,会把实现类中返回的Class名称都定义为bean。

    1.简单示例:  

    a.假设现在有一个接口HelloService,需要把所有它的实现类都定义为bean,而且它的实现类上是没有加Spring默认会扫描的注解的,比如@Component@Service等。

    b.定义了一个ImportSelector实现类HelloImportSelector,直接指定了需要把HelloService接口的实现类HelloServiceA和HelloServiceB定义为bean。

    c.定义了@Configuration配置类HelloConfiguration,指定了@Import的是HelloImportSelector。

    HelloService:

    package com.cy.service;
    
    public interface HelloService {
    
        void doSomething();
    }

    HelloServiceA:

    package com.cy.service.impl;
    
    import com.cy.service.HelloService;
    
    public class HelloServiceA implements HelloService {
    
        @Override
        public void doSomething() {
            System.out.println("Hello A");
        }
    }

    HelloServiceB:

    package com.cy.service.impl;
    
    import com.cy.service.HelloService;
    
    public class HelloServiceB implements HelloService {
    
        @Override
        public void doSomething() {
            System.out.println("Hello B");
        }
    }

    HelloImportSelector:

    package com.cy.service.impl;
    
    import org.springframework.context.annotation.ImportSelector;
    import org.springframework.core.type.AnnotationMetadata;
    
    public class HelloImportSelector implements ImportSelector {
    
        @Override
        public String[] selectImports(AnnotationMetadata importingClassMetadata) {
            return new String[]{HelloServiceA.class.getName(), HelloServiceB.class.getName()};
        }
    }

    HelloConfiguration:

    package com.cy.config;
    
    import com.cy.service.impl.HelloImportSelector;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Import;
    
    @Configuration
    @Import({HelloImportSelector.class})
    public class HelloConfiguration {
    }

    IndexController进行测试:

    @Controller
    public class IndexController {
    
        @Autowired
        private List<HelloService> helloServices;
    
        @ResponseBody
        @RequestMapping("/testImportSelector")
        public void testImportSelector() {
            helloServices.forEach(helloService -> helloService.doSomething());
        }
    }

    console:

    Hello A
    Hello B
  • 相关阅读:
    linux异常处理体系结构
    网站、架构、集群相关资源
    (转)分布式Web服务器架构的演变与技术需求
    B树、B树、B+树、B*树详解(转)
    (转)事件和路由事件概述
    LCID及Culture Name列表
    触摸键盘概述
    MySQL远端连接设置
    C#实现平衡多路查找树(B树) (转)
    CentOS6.3 LAMP运营环境安装
  • 原文地址:https://www.cnblogs.com/tenWood/p/15583628.html
Copyright © 2011-2022 走看看