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

后端 未结 4 454
北荒
北荒 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 12:08

    Since Vehicle is a @Model it is a runtime value, you won't be able to use it for autowiring values.

    The vehicle has to be passed to the service methods as an argument.

    public interface VehicleService { void doSomething(Vehicle vehicle); }

    Assuming both CarDao and TrainDAO are implementing the same VehicleDao Service, other wise it won't make much sense.

    So in your VehicleServiceImpl I would recommend you to write a method like getVehicleDao(Vehicle v){} to get the correct instance of the dao.

    public class VehicleServiceImpl implements VehicleService {
    
        @Resource(name="carDAO")
        private VehicleDao carDAO ;
    
    
        @Resource(name="trainDAO")
        private VehicleDao trainDAO ;
    
        private VehicleDao getDao(Vehicle v){
            if(v instanceof Train){
                return trainDao;
            } else if(v instanceof Car) {
                return carDao;
            } else {
                throw new RuntimeException("unsupported vehicle type");
            }
        }
    
        void doSomething(Vehicle vehicle){
            VehicleDao dao = getDao(vehicle);
            dao.doSomethind(vehicle);
        }
    }
    

提交回复
热议问题