Spring自定义限定符不起作用

时间:2016-01-10 18:26:16

标签: java spring

我试图在Spring中处理自定义限定符(4.2.4.RELEASE)。

我有一个界面:

    public interface CompactDisc {
    public void play();
}

和3个实现:

@Component
@Beatles
public class SgtPeppers implements CompactDisc {
    private String title = "Sgt. Pepper's Lonely Hearts Club Band";
    private String artist = "The Beatles";
    public void play() {
        System.out.println("Playing " + title + " by " + artist);
    }
}

@Component
@Metallica
@Metallica1986
public class MasterOfPuppets implements CompactDisc {
    @Override
    public void play() {
        System.out.println("Playing Master Of Puppets by Metallica");
    }
}

@Component
@Metallica
@Metallica1997
public class Fuel implements CompactDisc {
    @Override
    public void play() {
        System.out.println("Fuel by Metallica");
    }
}

我还创建了4个自定义限定符:

@Target({ElementType.CONSTRUCTOR, ElementType.FIELD,
        ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface Beatles {
}

@Target({ElementType.CONSTRUCTOR, ElementType.FIELD,
        ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface Metallica {
}


@Target({ElementType.CONSTRUCTOR, ElementType.FIELD,
        ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface Metallica1986 {
}

@Target({ElementType.CONSTRUCTOR, ElementType.FIELD,
        ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface Metallica1997 {
}

测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CDPlayerConfig.class)
public class CDPlayerTest {

    @Autowired
    @Metallica
    @Metallica1997
    private CompactDisc cd;

    @Test
    public void cdShouldNotBeNull() {
        assertNotNull(cd);
        cd.play();
    }
}

配置文件:

@Configuration
@ComponentScan
public class CDPlayerConfig {
}

但是当我运行它时,我看到了:

  

org.springframework.beans.factory.NoUniqueBeanDefinitionException:没有   定义[my.spring.CompactDisc]类型的限定bean:expected   单个匹配的bean但发现3:fuel,masterOfPuppets,sgtPeppers

为什么限定词对我不起作用?

0 个答案:

没有答案