【发布时间】:2014-12-22 12:52:46
【问题描述】:
我正在使用 Spring 框架(版本 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
可能的配置
- profile1,profile3
- profile2,profile3
有什么方法可以指定在任何情况下都应该实现哪个类(比如@Qualifier)?
为什么不@ActiveProfiles?
ActiveProfiles 是一个类级别的注解,用于声明 加载时应使用哪些活动 bean 定义配置文件 测试类的 ApplicationContext。
在这种情况下,我需要知道是否有任何方法可以根据配置文件指示应注入哪个类。
请看下面的例子。
@Controller
public class exampleController {
@Autowired
// Suppose that this can be possible
@Qualifier("{profile1, profile2}")
Iexample example
}
如果以这种方式指定的限定符可以工作,那么我将能够解决这个问题。
谢谢
【问题讨论】:
-
用@ActiveProfiles 注释你的测试用例
-
我已经更新了关于您的评论的问题。