一个接口多个实现,ApplicationContextAware

发布时间:2024年01月05日
@Component
public class TestApplicationContextAware implements ApplicationContextAware {
    /**
     * 其中 key 是 bean 的名称,value 是 bean 的实例
     */
    private Map<String,TestServer> map;

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

    public Map<String,TestServer> 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<String, TestServer> 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";
    }
}

测试

文章来源:https://blog.csdn.net/weixin_62971115/article/details/135407842
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。