@Produces return FacesContext --- why?

I hesitate to ask another question on the same topic, but at least for now I am reading, I think, the correct docs .

So this class:

class FacesContextProducer {
   @Produces @RequestScoped FacesContext getFacesContext() {
      return FacesContext.getCurrentInstance();
   }
}

      

From the welding docs, this technique does indeed apply to Glassfish via: GlassFish uses WELD as a reference implementation for JSR-299: Java Contexts and Dependency Injection for the Java EE Platform (CDI).

For the above class, where would it be used? Why do you need a separate class that @Produces FacesContext?

+3


source to share


2 answers


For the above class, where would it be used? Why is it trying to inject FacesContext?

I think this is done either for

  • consistency; or
  • testing.

ad 1. If you are trying to do a pure CDI, it looks good unless you use other dependency lookup mechanisms (like a static method getCurrentInstace()

). Note that there really is no need to define a manufacturer and use injection. It is just convenient and consistent with the use of CDI.



ad 2. explained by McDowell blog links, just imagine injection is done with CDI.

Why do you need a separate class that @Produces FacesContext?

It doesn't have to be a separate class, you can have a single class producing multiple beans. It just helps the clarity of the code to keep it separate.

+7


source


You might want to introduce FacesContext

to avoid direct dependency on a static method getCurrentInstance()

to make mocking and unit testing easier.



I wrote a bit about this for my own JSF dependency nesting mechanisms here .

+6


source







All Articles