Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring@Profile和自动布线匹配_Java_Spring - Fatal编程技术网

Java Spring@Profile和自动布线匹配

Java Spring@Profile和自动布线匹配,java,spring,Java,Spring,我正在使用SpringFramework(3.2版),在我的应用程序中进行一些重构之后,我遇到了配置文件配置自动连接的问题 假设我有一个由两个类实现的接口。这些类根据环境设置实现一系列方法。实际上,我有3个不同的配置文件属性profile1、profile2和profile3。使用概要文件工作得很好,但在这里,我第一次遇到了一个小问题,因为由于找到了2个候选对象,类无法被注入 public interface Iexample { public void doSomething(); }

我正在使用SpringFramework(3.2版),在我的应用程序中进行一些重构之后,我遇到了配置文件配置自动连接的问题

假设我有一个由两个类实现的接口。这些类根据环境设置实现一系列方法。实际上,我有3个不同的配置文件属性profile1、profile2和profile3。使用概要文件工作得很好,但在这里,我第一次遇到了一个小问题,因为由于找到了2个候选对象,类无法被注入

public interface Iexample {
  public void doSomething();
}

@Profile("profile1")
public class classA implements Iexample {
  doSomething(){..}
}

@Profile("{profile2, profile3}")    
public class ClassB implements Iexample {
  doSomething(){..}
}

public class Test1 {

@Autowired
Iexample example; //Should use implementation based on profile1 or profile2

}

public class Test2 {

@Autowired
Iexample example; //Should use implementation based on profile3 only

}
配置的当前属性:

spring.profiles.active= profile1,profile3
可能的配置

  • 档案1,档案3
  • 档案2,档案3
有没有办法指定在任何情况下都应该实现哪个类(比如@Qualifier)

为什么不@ActiveProfiles呢

ActiveProfiles是用于声明 加载时应使用哪些活动bean定义配置文件 测试类的ApplicationContext

在这种情况下,我需要知道是否有任何方法根据配置文件指示应该注入哪个类

请看下面的例子

@Controller
public class exampleController {
    @Autowired
    // Suppose that this can be possible
    @Qualifier("{profile1, profile2}")
    Iexample example
}
如果以这种方式指定的限定符可以工作,那么我将能够解决这个问题


谢谢

您可以用注释标记一个bean,以指定它作为autowire候选对象应该具有优先权。javadoc是针对Spring4的,但是Spring3.2的文档也提到了这个注释

我考虑使用@Primary注释,但是在某些情况下,我无法确定哪个实现可以是默认的。当我完全确定我需要什么的时候,唯一的地方就是在类中注入接口。请查看Test1和Test2类中的注释。无论如何,谢谢你的提示。用@ActiveProfile注释你的测试用例我已经更新了关于你评论的问题。