@ComponentpublicclassMyServiceFactory{privatefinalMap<String,MyService>serviceMap;@AutowiredpublicMyServiceFactory(List<MyService>services){serviceMap=services.stream().collect(Collectors.toMap(service->service.getClass().getSimpleName().replace("MyServiceImpl","").toLowerCase(),service->service));}publicMyServicegetService(Stringtype){MyServiceservice=serviceMap.get(type.toLowerCase());if(service==null){thrownewIllegalArgumentException("Unknown service type: "+type);}returnservice;}}
使用工厂类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@RestController@RequestMapping("/api")publicclassMyController{privatefinalMyServiceFactorymyServiceFactory;@AutowiredpublicMyController(MyServiceFactorymyServiceFactory){this.myServiceFactory=myServiceFactory;}@GetMapping("/process")publicResponseEntity<String>process(@RequestParamStringtype){MyServicemyService=myServiceFactory.getService(type);myService.process();returnResponseEntity.ok("Processing done by "+type);}}