7.3.2. 使用 Qualifier 解决 Ambiguous Injection

您可以使用限定符解决模糊注入问题。阅读有关Ambiguous 或 Unsatisfidened 依赖项模糊注入的更多信息

以下示例模糊不清,并且有两个 Welcome 实施 一种是转换,另一个是没有实现。需要指定注入以使用转换 Welcome

示例:Ambiguous Injection

public class Greeter {
  private Welcome welcome;

  @Inject
  void init(Welcome welcome) {
    this.welcome = welcome;
  }
  ...
}

使用 Qualifier 解析 Ambiguous Injection
  1. 要解决模糊注入,请创建一个名为 @Translating 的限定注释:

    @Qualifier
    @Retention(RUNTIME)
    @Target({TYPE,METHOD,FIELD,PARAMETERS})
    public @interface Translating{}
  2. 使用 @ Translating 注释给转换 Welcome 标注:

    @Translating
    public class TranslatingWelcome extends Welcome {
        @Inject Translator translator;
        public String buildPhrase(String city) {
            return translator.translate("Welcome to " + city + "!");
        }
        ...
    }
  3. 请求注入中的 Welcome。您必须明确请求合格的实施,类似于工厂方法模式。这种不确定性是在注入点解决的。

    public class Greeter {
      private Welcome welcome;
      @Inject
      void init(@Translating Welcome welcome) {
        this.welcome = welcome;
      }
      public void welcomeVisitors() {
        System.out.println(welcome.buildPhrase("San Francisco"));
      }
    }