java - 基于RequestBody参数获取Java Spring boot中的特定bean
问题描述
@RequestBody
在我的 Spring Boot 应用程序中,我想根据接收到的值获取特定类的对象/bean 。有没有办法做同样的事情
界面
public interface Vehicle{
public String drive();
}
接口的实现
@Component
public class Car implements Vehicle {
public String drive(){
return "Driving a car";
}
}
@Component
public class Bike implements Vehicle {
return "Riding a Bike";
}
现在在我的控制器中,根据请求正文,我想获取 EitherCAR
或Bike
.
有没有办法做同样的事情
控制器
@RestController
@RestMapping('type-of-vehicle')
public class VehicleSelectController{
@PostMapping
public String identify_Vehicle_Selected(@RequestBody vehicletype vehicletype_data){
/* ## Code to get the bean of vehicle type sent in the RequestBody */
// example vehicletype_data selected vehicle is car
// we get the bean of the 'CAR' class
// Returns the correct implementation of the type of vehicle selected by user
return vehicle.drive();
}
}
是否有任何注释可以用来实现更多我试图避免根据收到的车辆类型返回正确对象的配置类
我在想沿着这条线的东西
错误的执行方式
@RestController
@RestMapping('type-of-vehicle')
public class VehicleSelectController{
@PostMapping
public String identify_Vehicle_Selected(@RequestBody vehicletype vehicletype_data){
@Autowired
@Qualifiyer('${vehicletype_data}')
Vehicle vehicle_object
return vehicle_object.drive();
}
}
有没有一种方法可以做类似于错误实现的事情
解决方案
您可以使用工厂模式。为获取 Vehicle bean 创建一个 bean 工厂。
@Component
public class VehicleFactory{
@Autowired
@Qualifier("bike") // bean name is same as class name with the first letter being lowercase
private Vehicle bike;
@Autowired
@Qualifier("car")
private Vehicle car;
public Vehicle getVehicle(VehicleType vehicleType){
if(vehicleType == VehicleType.CAR){ // Assuming VehicleType is an enum
return car;
} else if (vehicleType == VehicleType.BIKE){
return bike;
} else {
throw new IllegalArgumentException("No bean available for the type " + vehicleType);
}
}
}
现在在你的控制器中,
@RestController
@RestMapping('type-of-vehicle')
public class VehicleSelectController{
@Autowired
VehicleFactory vehicleFactory;
@PostMapping
public String identify_Vehicle_Selected(@RequestBody vehicletype vehicletype_data){
return vehicleFactory.getVehicle(vehicletype_data).drive(); // handle the exception as needed
}
}
推荐阅读
- qt - Qt QML 如何找到形状的宽度和高度?
- python - ValueError: 以 10 为底的 long() 的无效文字:'$10592956'
- javascript - Which Event.target Property Should I Use?
- angular - 如何在Angular组件中向传单地图添加标记
- sql - 使用案例语句插入
- java - 不使用 if 就抛出异常 - Java
- python - QThreadPool 是按顺序运行而不是并行运行,是什么导致我的代码线程不并行运行?
- javascript - 折叠标题与滚动时的动态高度
- javascript - 在统一开始使用 javaScript 进行游戏开发之前,我是否需要了解任何其他语言?
- swift-playground - 如何在操场上故意退出?