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

后端 未结 4 459
北荒
北荒 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:21

    There is an cleaner option to accomplish this strategy. We know Spring is smart enough to inject where it sees a bean that it has control over, so when it sees your VehicleDAO with an @Autowire or @Resource annotation, it will correctly inject that concrete implementation.

    Keeping that in mind, this will work anywhere you ask Spring to perform dependency injection, using a Map<> or a List<> for instance.

    // Injects the map will all VehicleDAO implementations where key = the
    // concrete implementation (The default name is the class name, otherwise you 
    // can specify the name explicitly).
    @Autowired
    private Map vehicleDAO;
    
    // When you want to use a specific implementaion of VehicleDAO, just call the  
    // 'get()' method on the map as in:
    ...
    vehicleDAO.get("carDAO").yourMethod();
    ...
    

提交回复
热议问题