Spring 3 - Dynamic Autowiring at runtime based on another object attribute

后端 未结 4 455
北荒
北荒 2020-12-08 11:27

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

4条回答
  •  借酒劲吻你
    2020-12-08 11:59

    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.

提交回复
热议问题