我有 2 个实现 InterfaceA 的类
@Service("classA")
class ClassA implements InterfaceA
@Service("classB")
class ClassB implements InterfaceA
我需要加载两个 bean。但是,在 C 类和 D 类中,我需要指定我需要的 bean
class ClassC {
@Autowired
@Qualifier("classA")
private InterfaceA interf;
}
class ClassD {
@Autowired
@Qualifier("classA")
private InterfaceA interf;
}
但是,我有 2 个配置文件,profile1 和 profile2。如果我使用 -Dspring.profiles.active=profile1,我应该为 classC 和 classD 使用限定符“classA”。如果我使用 -Dspring.profiles.active=profile2,我应该使用“classB”作为限定符。此外,另一个 ClassE 应该始终使用 classB,而不管配置文件如何。你能告诉我应该怎么做吗?
最佳答案
我就是这样做的。我创建了一个配置类
@Configuration
public class ConfigClass {
@Autowired
private ClassB classB;
@Profile("profile1")
@Qualifier("myclass")
@Bean
private InterfaceA classAtProfile1() {return new ClassA();}
@Profile("profile2")
@Qualifier("myclass")
@Bean
private InterfaceA classAtProfile2() {return classB;}
}
class ClassA implements InterfaceA
@Service("classB")
class ClassB implements InterfaceA
这样,我就可以根据配置文件 Autowiring InterfaceA
@Autowired
@Qualifier("myclass")
private InterfaceA myclass;
虽然E类仍然可以引用B类
@Component
public class ClassE {
@Autowired
ClassB classB;
...
}
关于java - 给定配置文件 Autowiring 特定的 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51978547/