官术网_书友最值得收藏!

Programmatic lookup of contextual instances

We may encounter some situations where it's not convenient to obtain a contextual instance through injection, which are as follows:

  • Either the bean type or qualifiers of an injection point may vary at runtime
  • In some deployments, there may be no bean that satisfies the bean type and qualifiers of an injection point
  • We want to loop through all the beans of a specific bean type

For these situations we obtain an instance of Instance parameterized to the bean type we require:

@Inject
Instance<BookSearch> bookSearch;

To retrieve a contextual instance:

BookSearch search = bookSearch.get();

We can also alter the bean types that will be retrieved from Instance by adding qualifiers either to the injection point or passing them to select().

Specifying qualifiers at the injection is simple:

@Inject
@Book(Category.NONFICTION)
Instance<BookSearch> bookSearch;

But sometimes it's necessary for the qualifiers to be specified dynamically. For us to use dynamic qualifiers we need to suppress the @Default qualifier by specifying @Any on the injection point:

@Inject
@Any
Instance<BookSearch> bookSearch;

Now, we need to create an instance of our annotation @Book so it can be passed to select(). However, as it's just an interface we aren't able to create one with new, we need an implementation of that interface. CDI helps us out by providing AnnotationLiteral, a helper class for creating annotation implementations. Our annotation implementation is:

public class BookLiteral extends
AnnotationLiteral<Book> implements Book {
  private final Category category;
  private final String description;

  public BookLiteral(Category category, String description) {
    this.category = category;
    this.description = description;
  }

  public Category value() {
    return category;
  }

  public String description() {
    return description;
  }
}

So retrieving a bean from Instance with a dynamic qualifier is:

Annotation qualifier = fiction ? new BookLiteral(Category.FICTION,
"") : new BookLiteral(Category.NONFICTION, "Non Fiction");
BookSearch search = bookSearch.select(qualifier).get();

If we had separate qualifiers for fiction and nonfiction books, such as @NonFiction and @Fiction, instead of @Book with a Category, we could use dynamic qualifiers without extending AnnotationLiteral by creating anonymous classes:

bookSearch.select(new AnnotationLiteral<NonFiction>() {}).get();
Tip

"You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com . If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you."

主站蜘蛛池模板: 贵溪市| 岳池县| 凌源市| 文成县| 昭苏县| 闽清县| 金川县| 富蕴县| 宁武县| 肥西县| 那坡县| 襄汾县| 扎鲁特旗| 沅陵县| 金堂县| 子长县| 东丽区| 敦化市| 南昌市| 广州市| 阿城市| 钟祥市| 鸡东县| 襄汾县| 林芝县| 和政县| 连江县| 西盟| 呼图壁县| 会宁县| 达日县| 甘南县| 札达县| 沂源县| 堆龙德庆县| 昭苏县| 无棣县| 长治市| 波密县| 湖南省| 城步|