Java 在spring boot中使用同一个bean访问不同的实现/组件
现在,在主Spring引导应用程序中,我将“live”配置文件设置如下Java 在spring boot中使用同一个bean访问不同的实现/组件,java,spring,components,implementation,profile,Java,Spring,Components,Implementation,Profile,现在,在主Spring引导应用程序中,我将“live”配置文件设置如下 @Configuration @Profile("live") public class LiveProfileConfig{ @Bean public BaseInterface commonInterface(){ return new LiveComponent(); } } @Configuration @Profile("test") public class Test
@Configuration
@Profile("live")
public class LiveProfileConfig{
@Bean
public BaseInterface commonInterface(){
return new LiveComponent();
}
}
@Configuration
@Profile("test")
public class TestProfileConfig{
@Bean
public BaseInterface commonInterface(){
return new TestComponent();
}
}
然后根据活动配置文件调用其中一个实现来使用组件
@ContextConfiguration(classes = {LiveProfileConfig.class, TestProfileConfig.class},loader=AnnotationConfigContextLoader.class)
@ActiveProfiles(value="live")
现在,我想访问一个基于活动概要文件的组件方法(即LiveComponent/TestComponent)
它在JUnit测试中工作,但当我尝试用Spring启动应用程序运行它时,它给出了以下错误
需要一个bean,但是发现了2个,考虑标记一个 将bean更新为@Primary,更新使用者以接受多个bean,或 使用@Qualifier标识应该使用的bean
任何帮助?这是不可能的,如果只有
live
profile处于活动状态,那么spring将忽略test
profile bean。使用System.getProperty()
检查spring.profiles.active
属性的值。它应该具有预期的配置文件值。是的,我也希望这样做,比如当活动配置文件处于活动状态时,然后仅访问LiveComponent方法。
@Service
public class AnotherImpl implements AnotherInterface {
@Autowired
BaseInterface commonInterface;
}