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
Interface
public interface Vehicle{
public String drive();
}
Implementation of The interface
@Component
public class Car implements Vehicle {
public String drive(){
return "Driving a car";
}
}
@Component
public class Bike implements Vehicle {
return "Riding a Bike";
}
Now in my controller based on the request body I want to get the bean of Either CAR
or Bike
.
Is there a way to do the same
Controller
@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
I was thinking something along this line
Wrong-way of Implementation
@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