两个(或多个)接口实现的依赖注入

时间:2019-07-05 14:07:46

标签: dependency-injection cdi java-ee-7

在多次实现同一接口( Java EE 7 )的情况下,注入正确的bean时遇到一些问题。

我已经尝试过本指南的内容:https://docs.jboss.org/weld/reference/1.0.0/en-US/html/injection.html

public interface BookDescription {
    public String getDescription();
}

@ShortOne
public class BookDescriptionShortImpl implements BookDescription {

    @Override
    public String getDescription() {
    return "This is a short description";
    }
}

@LongOne
public class BookDescriptionLongImpl implements BookDescription {

    @Override
    public String getDescription() {
        return "This is a long, long description...";
    }
}

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE})
@Documented
public @interface LongOne {
}

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE})
@Documented
public @interface ShortOne {
}

public class Book {
    @Inject
    @LongOne
    private BookDescription bookDescription;
}

当我使用Maven构建.war时,我得到了:

Ambiguous dependencies for type BookDescription with qualifiers @Default错误。

您是否对上面的代码段有任何想法,如果这是注入依赖关系的正确方法?

感谢您的回答,如果需要,可以随时编辑此问题。

0 个答案:

没有答案