gpt4 book ai didi

java - Spring @Profile 和 Autowiring 匹配

转载 作者:行者123 更新时间:2023-12-02 09:46:43 24 4
gpt4 key购买 nike

我正在使用 Spring 框架(版本 3.2),在我的应用程序中进行一些重构后,我遇到了使用配置文件配置 Autowiring 的问题。

假设我有一个由两个类实现的接口(interface)。这些类根据环境设置实现一系列方法。实际上我有 3 个不同的配置文件属性 profile1、profile2 和 profile3。使用配置文件效果很好,但这是我第一次遇到一个小问题,因为由于找到 2 个候选者而无法注入(inject)类。

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 is a class-level annotation that is used to declare which active bean definition profiles should be used when loading an ApplicationContext for test classes.

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

请看下面的示例。

@Controller
public class exampleController {
@Autowired
// Suppose that this can be possible
@Qualifier("{profile1, profile2}")
Iexample example
}

如果以这种方式指定的限定符可能有效,那么我将能够解决此问题。

谢谢

最佳答案

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

关于java - Spring @Profile 和 Autowiring 匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27603141/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com