Spring wiring conditional to an environment

后端 未结 3 1734
天涯浪人
天涯浪人 2020-12-21 17:49

With Spring wiring, if I have multiple implementations of an interface, I can use @Qualifier to specify which one I want.

E.g., assuming that I have a



        
相关标签:
3条回答
  • 2020-12-21 17:59

    You can injection both implementation and choose which one you need by parameter {spring.profiles.active}, such like this code :

    @autowired
    private Car Toyota;
    @autowired
    private Car Bmv;
    
    public Car getCar(){
      if(spring.profiles.active is local){
            return Toyota;
      }else{
            return  bmv;
      }
    }
    
    0 讨论(0)
  • 2020-12-21 18:08

    Ah, the solution is actually quite simple:

    @Component
    @Qualifier("Bmv")
    @Profile("!dev")
    public class Bmv implements Car
    

    and

    @Component
    @Qualifier("Toyota")
    @Profile("dev")
    public class Toyota implements Car
    

    This way, the wiring of Car will use Toyota for dev environment, and Bmv otherwise.

    0 讨论(0)
  • 2020-12-21 18:08

    Spring 3.1 introduced environment profiles: http://blog.springsource.com/2011/02/11/spring-framework-3-1-m1-released/

    I personally do not like Qualifiers and using them the way you proposed in the code actually couples to the implementation rather than decouple. You can use the @Autowired element like Jason proposed, but couple that with the bean profiles like so:

    <beans profile="dev"> <jdbc:embedded-database id="dataSource"> <jdbc:script location="classpath:com/bank/config/sql/schema.sql"/> <jdbc:script location="classpath:com/bank/config/sql/test-data.sql"/> </jdbc:embedded-database> </beans>

    and then when you create the environment you specify a profile:

    <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>spring.profiles.active</param-name> <param-value>production</param-value> </init-param> </servlet>

    0 讨论(0)
提交回复
热议问题