一个接口多个实现,ApplicationContextAware

@Component
public class TestApplicationContextAware implements ApplicationContextAware {
    /**
     * 其中 key 是 bean 的名称,value 是 bean 的实例
     */
    private Map map;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        map = applicationContext.getBeansOfType(TestServer.class);
    }

    public Map getMap(){
        return map;
    }

    public TestServer getServer(String key){
        return map.get(key);
    }
}

控制层

@RestController
@RequestMapping("/test")
public class TestController {
    /*@Resource
    private TestServer testServer;*/

    @Resource
    private TestApplicationContextAware contextAware;

    @GetMapping("t01")
    public String main(String bo) {
        Map map = contextAware.getMap();
        //TestServer server = contextAware.getServer(bo);
        TestServer server = map.get(bo);
        return server.getTest();
    }
}

服务层

public interface TestServer {
    public String getTest();
}
@Service("A")
public class TestServerImpl implements TestServer {
    @Override
    public String getTest() {
        return "实现A";
    }
}
@Service("B")
public class TestServer01Impl implements TestServer {
    @Override
    public String getTest() {
        return "实现B";
    }
}

测试

一个接口多个实现,ApplicationContextAware_第1张图片

一个接口多个实现,ApplicationContextAware_第2张图片

你可能感兴趣的:(java,前端,数据库)