Search code examples
jsfjakarta-eedependency-injectionjava-ee-6cdi

Inject a Java object in a JSF Named bean


I have a JSF2 bean used as a controller for my view:

@Named
@SessionScoped
public class PosController implements Serializable {

  @EJB FatturaFacade fatturaFacade;

  // ...
}

As you can see I already can inject one of my EJBs (used as a dao wrapper) inside it, but what's the way for injecting a "simple" object? And what if I have different implementations as follows?

interface Retriever;
class WebServiceRetriever implements Retriever;
class FileRetriever implements Retriever;

I saw the @interface annotation, but I didn't understand it well.


Solution

  • Assuming you have a full Java EE 6 platform the best approach is to use CDI's @Inject.

    The simplest mechanism would be to use the concrete types:

    public class Bean {
      @Inject
      private WebServiceRetriever webServiceRetriever;
    
      @Inject
      private FilesRetriever filesRetriever;
    
      //etc.
    

    For multiple implementations of the same interface you can create @Qualifier annotations. Their usage is explained in the Using Qualifiers section of the Java EE 6 tutorial.

    A @Files qualifier:

    @Qualifier
    @Retention(RUNTIME)
    @Target({TYPE, METHOD, FIELD, PARAMETER})
    public @interface Files {}
    

    The FileRetriever implementation:

    @Files
    public class FileRetriever implements Retriever {}
    

    Disambiguation of the Retriever implementations in the injection target:

    public class Bean {
      @Inject @WebServices
      private Retriever webServiceRetriever;
    
      @Inject @Files
      private Retriever filesRetriever;
    
      //etc.
    

    There is a post on my blog on using JSF with CDI that you might find useful.