I am working on a Spring 3.1 MVC application and for one of my scenarios, I had to write two implementations of a DAO. I would like to know how to autowire this in a service
My solution would be as follows:
a method isResponsibleFor in the VehicleDao interface:
interface VehicleDao {
public boolean isResponsibleFor(Vehicle vehicle);
}
example implementation:
@Repository
class CarDAO implements VehicleDAO {
public boolean isResponsibleFor(Vehicle vehicle) {
return "CAR".equals(vehicle.getType());
}
}
then autowire a list of all VehicleDao-implementations in the VehicleService:
public class VehicleServiceImpl implements VehicleService {
@Autowired
private List vehicleDaos;
private VehicleDao daoForVehicle(Vehicle vehicle) {
foreach(VehicleDao vehicleDao : vehicleDaos) {
if(vehicleDao.isResponsibleFor(vehicle) {
return vehicleDao;
}
}
throw new UnsupportedOperationException("unsupported vehicleType");
}
@Transactional
public void save(Vehicle vehicle) {
daoForVehicle(vehicle).save(vehicle);
}
}
This has the advantage that you don't need to modify the service when you are adding a new vehicleType at a later time - you just need to add a new VehicleDao-implementation.