【问题标题】:Spring @Profile and autowiring matchingSpring @Profile 和自动装配匹配
【发布时间】: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 注释你的测试用例
  • 我已经更新了关于您的评论的问题。

标签: java spring


【解决方案1】:

您可以使用@Primary 注释标记一个bean,以指定它应该优先作为自动装配候选者。 javadoc 适用于 Spring 4,但 Spring 3.2 的文档也提到了该注释。

【讨论】:

  • 我考虑使用@Primary 注释,但是在某些情况下我无法确定哪个实现可以是默认的。当我完全确定我需要什么时,唯一的地方是在我注入接口的类中。请查看 Test1 和 Test2 类中的 cmets。无论如何感谢您的提示。
猜你喜欢
  • 2018-01-27
  • 2019-05-03
  • 1970-01-01
  • 1970-01-01
  • 2016-10-30
  • 2012-08-13
  • 2012-02-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多