首页 > 解决方案 > 基于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";
}

现在在我的控制器中,根据请求正文,我想获取 EitherCARBike.

有没有办法做同样的事情

控制器

@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();

   }
}

有没有一种方法可以做类似于错误实现的事情

标签: javaspringspring-bootserver

解决方案


您可以使用工厂模式。为获取 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
    }
}

推荐阅读