创建实现相同接口的两个bean

时间:2016-06-28 13:21:12

标签: java spring javabeans autowired

我想创建两个实现相同接口的bean。 Bean有名称,但是当我使用@Qualifier注释时

得到的错误如下:

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

这是我的配置类。

@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);
}
}

这是我的考试班。

@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());
}
}

编辑: 我的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();
}
}

2 个答案:

答案 0 :(得分:2)

将您的代码更改为以下内容:

@Bean
public MediaPlayer cdPlayer(@Qualifier("bbb") CompactDisc cd){
    return new CDPlayer(cd);
}

答案 1 :(得分:0)

spring试图在这里注入一个bean Compactdisc

@Bean
public MediaPlayer cdPlayer(CompactDisc cd){
    return new CDPlayer(cd);
}

您必须将@Qualifier注释添加到CompactDisc

另一种方法是从CDplayer构造函数中删除参数并将其作为参数添加到play方法