Dependent beans for producers

In creating a new bean with a producer, there may be situations in which we do not want an existing instance of a bean to be injected into our producer, but would prefer an instance that is dependent on the scope of the bean that produced it.

Taking our example from the previous section, we can resolve the problem of a requestscoped bean being promoted to the session scope with the following producer:

@Produces
@Preferred
@SessionScoped
public BookSearch getSearch
(@New FictionSearch fs, @New NonFictionSearch nfs) {

  switch (searchType) {
    case FICTION:
      fs.setDescription("Hello from Fiction Search!");
      return fs;
    case NONFICTION:
      return nfs;
    default:
      return null;
  }
}

Deploying our example and accessing http://localhost:8080/chapter5/index.jsf ...

Get JBoss Weld CDI for Java Platform now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.