使用Map获取实现该接口的实现类
1,创建MapService接口
public interface MapService {
String saySomething();
}
2,创建MapService实现类
MapServiceImpl1.java
@Service
public class MapServiceImpl1 implements MapService {
@Override
public String saySomething() {
return "MapServiceImpl----1";
}
}
// 如果未指定value,获取实例时将默认为开头小写 mapServiceImpl2
@Service(value = "MapServiceImpl2")
public class MapServiceImpl2 implements MapService {
@Override
public String saySomething() {
return "MapServiceImpl----2";
}
}
3,创建MapServiceFactory
@Service
public class MapServiceFactory {
@Autowired
Map<String, MapService> mapservice;
public MapService getInstance(String name){
MapService mapService = mapservice.get(name);
if( mapService == null){
System.out.println("没有此实现类");
return null;
}
return mapService;
}
}
4,创建Controller
@RestController
public class MapController {
@Autowired
MapServiceFactory mapservice;
@GetMapping("/mapservice")
public Map<String, String> mapservice(){
Map<String, String> map = new HashMap<>();
MapService mapService = mapservice.getInstance("mapServiceImpl1");
map.put("mapServiceImpl1", mapService.saySomething());
mapService = mapservice.getInstance("MapServiceImpl2");
map.put("mapServiceImpl2", mapService.saySomething());
return map;
}
}
测试结果如下: