根据 RequestBody 参数获取 Java Spring boot 中的特定 bean [英] Get a specific bean in Java Spring boot based on RequestBody parameter
问题描述
在我的 Spring Boot 应用程序中,我想根据接收到的 @RequestBody
值获取特定类的对象/bean.有没有办法做同样的事情
In my spring boot application, I want to get an object/bean of a specific class based on the @RequestBody
value that is received. Is there a way to do the same
界面
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";
}
现在在基于请求正文的控制器中,我想获取 CAR
或 Bike
的 bean.
Now in my controller based on the request body I want to get the bean of Either CAR
or 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();
}
}
是否有任何注释可用于实现相同的更多功能,我试图避免创建一个根据收到的车辆类型返回正确对象的配置类
Are there any annotations that can be used to achieve the same more of I am trying to avoid making a config class that returns the correct object based on the vehicle type received
我一直在思考这个问题
错误的实现方式
@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();
}
}
有没有办法做类似不正确的实现
Is there a method to do something similar to the incorrect implementation
推荐答案
我发现了类似的问题:通过限定符从 ApplicationContext 中获取 bean
如果它不能解决您的问题,请尝试以下操作:
If it does not solve your problem, maybe try something like:
- 向
Vehicle
接口添加方法,通过请求的给定数据检查它是否是目标车辆:
- Add method to
Vehicle
interface that check whether it is target vehicle by given data from request:
boolean isTargetVehicle(final string valueFromRequest);
汽车车辆实施示例:
public boolean isTargetVehicle(final string valueFromRequest) {
return "car".equals(valueFromRequest);
}
- 然后在您的控制器/服务中使用车辆注入集合:
@Autowired
Collection<Vehicle> vehicles;
- 在控制器中添加仅在目标车辆上调用
drive
方法的实现.它从drive
方法返回值,否则如果找不到车辆支持则抛出异常:
- Add implementation in controller that invokes
drive
method only on target vehicles. It returns value fromdrive
method, otherwise throws exception if vehicle support is not found:
vehicles.stream().filter(v -> v.isTargetVehivle(dataFromRequest)).map(Vehicle::drive).findFirst().orElseThrow(() -> new Exception("vehicle not supported"));
通过这种方法,您无需修改现有代码即可轻松添加新车辆.另外最好使用构造函数注入.
In this approach you can easily add new vehicle without modifying existing code. And in addition it is better to use constructor injection.
这篇关于根据 RequestBody 参数获取 Java Spring boot 中的特定 bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!