@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";
}
}
测试