[英]Creating two beans implementing the same interface
I want to create two bean implementing the same interface. 我想创建两个实现相同接口的bean。 Beans have names, but when I use
@Qualifier
annotation Bean有名称,但是当我使用
@Qualifier
批注时
got error like: 有类似的错误:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'cdPlayer' defined in soundsystem.CDPlayerConfig: Unsatisfied dependency expressed through method 'cdPlayer' parameter 0: No qualifying bean of type [soundsystem.CompactDisc] is defined: expected single matching bean but found 2: sss,aaa; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [soundsystem.CompactDisc] is defined: expected single matching bean but found 2: sss,aaa
This is my configuration class. 这是我的配置类。
@Configuration
public class CDPlayerConfig {
@Bean(name="bbb")
public CompactDisc blankDisc(){
List<String> list = new LinkedList<>();
list.add("qwer");
list.add("qazw");
return new BlankDisc("one", "two", list);
}
@Bean(name="aaa")
public CompactDisc sgtPeppers(){
return null;
}
@Bean
public MediaPlayer cdPlayer(CompactDisc cd){
return new CDPlayer(cd);
}
}
This is my test class. 这是我的测试课。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=CDPlayerConfig.class)
public class CDPlayerTest {
@Rule
public final SystemOutRule log = new SystemOutRule().enableLog();
@Autowired
private MediaPlayer player;
@Autowired
@Qualifier("aaa")
private CompactDisc cd;
@Test
public void cdShouldNotBeNull(){
assertNotNull(cd);
}
@Test
public void play(){
player.play();
assertEquals("XYZ", log.getLogWithNormalizedLineSeparator());
}
}
Edit: My CDPlayer class 编辑:我的CDPlayer类
public class CDPlayer implements MediaPlayer {
private CompactDisc cd;
@Autowired
public CDPlayer(CompactDisc cd){
this.cd = cd;
}
@Override
public void play() {
// TODO Auto-generated method stub
cd.play();
}
}
Change your code to the following: 将您的代码更改为以下内容:
@Bean
public MediaPlayer cdPlayer(@Qualifier("bbb") CompactDisc cd){
return new CDPlayer(cd);
}
spring tries to inject a bean Compactdisc
here: 春天试图在这里注入一个bean
Compactdisc
:
@Bean
public MediaPlayer cdPlayer(CompactDisc cd){
return new CDPlayer(cd);
}
You have to add the @Qualifier
Annotation to CompactDisc
. 您必须将
@Qualifier
批注添加到CompactDisc
。
An other way is to remove the parameter from CDplayer constructor and put it as a parameter to the play method 另一种方法是从CDplayer构造函数中删除参数,并将其作为播放方法的参数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.