弹簧布线以环境为条件

时间:2013-05-17 02:15:58

标签: java spring autowired

使用Spring连接,如果我有多个接口实现,我可以使用@Qualifier来指定我想要的那个。

,例如,假设我有

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

@Component
@Qualifier("Bmv")
public class Bmv implements Car

然后我可以选择具体的实现:

  @Qualifier("Toyota") Car car 

但是有没有办法根据环境选择实施?

即。如果我将spring.profiles.active设置为local,那么我将选择Car的'Toyota'实现,但如果spring.profiles.active设置为dev或stage,那么我将选择Car的'Bmv'实现?

可以理解确切语法的一个例子。

3 个答案:

答案 0 :(得分:3)

啊,解决方案实际上非常简单:

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

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

这样,Car的布线将使用丰田进行开发环境,否则使用Bmv。

答案 1 :(得分:2)

您可以注入两个实现,并通过参数{spring.profiles.active}选择您需要的实现,如下代码:

@autowired
private Car Toyota;
@autowired
private Car Bmv;

public Car getCar(){
  if(spring.profiles.active is local){
        return Toyota;
  }else{
        return  bmv;
  }
}

答案 2 :(得分:1)

Spring 3.1引入了环境配置文件:http://blog.springsource.com/2011/02/11/spring-framework-3-1-m1-released/

我个人不喜欢限定符,并且在代码中提出的方式使用它们实际上与实现耦合而不是解耦。您可以使用像Jason提议的@Autowired元素,但将其与bean配置文件结合使用,如下所示:

<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>

然后在创建环境时指定配置文件:

<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>