【发布时间】:2020-06-26 20:17:16
【问题描述】:
我正在学习 Spring Boot,我想为我的问题找到一个更优雅的解决方案。
在特定服务中,我需要根据 Enum 值调用正确的 impl。
现在我正在做这样的事情:
@Service
public class VehicleHandlerService {
@Autowired
private CarService carService; // implements VehicleService interface
@Autowired
private BusService busService; // implements VehicleService interface
@Autowired
private TruckService truckService; // implements VehicleService interface
public Vehicle doSomething(VehicleType type) {
return getService(type).doSomething();
}
// I might need have different Data types for specific Service here, like a CarData, BusData, TruckData, etc...
public .???. otherMethod(VehicleType type, Data data) {
return getService(type).otherMethod(data);
}
private VehicleService getService(VehicleType type) {
if(VehicleType.CAR.equals(type)) {
return carService;
} else if(VehicleType.BUS.equals(type)) {
return busService;
} else if(VehicleType.TRUCK.equals(type)) {
return truckService;
}
//throw exception
}
}
我想知道我们是否有一种更类似于 Spring 的方式来做到这一点?就像注入地图一样:
@Autowired
private Map<VehicleType, VehicleService> services;
除了有方法之外,还要使用它。
如果我以后需要添加更多 VehicleService impl,我也必须继续手动添加它们。
你们如何在 Spring 上处理此类问题以避免重复代码和一堆 if/else?
欢迎任何可以让我学习 Spring 功能的建议!
【问题讨论】:
标签: java spring spring-boot