Why are there different bean management annotations

cdijsfmanaged-bean

What is the difference between

import javax.annotation.ManagedBean;
import javax.enterprise.context.SessionScoped;

and

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

?

Best Answer

  1. javax.enterprise.context.SessionScoped(JSR 346) and all other annotations under the javax.enterprise.context.* package maintain the context of CDI. CDI provides an alternative, versatile and more powerful mechanism for dependency injection, bean and general resource management within the Java EE space. It's an alternative to JSF managed beans and it's set to even supersede the JSF bean management mechanism in the coming version of JSF.

    Currently, JSF and CDI annotated beans are interchangeable within any given Java EE web application (given a handful of minor restrictions). CDI annotated beans however, extend far beyond the realm of the web tier, which is why the Java EE spec is evolving to make CDI the standard bean and DI mechanism.

    While CDI might be an obvious choice for all Java EE development, JSF managed beans are portable across servlet containers (Tomcat) and application servers (Glassfish, JBoss, etc.). CDI beans can live within only full application servers. With some legwork however, Tomcat 7 can be wired to support CDI.

    Specifically, javax.enterprise.context.SessionScoped is the parallel implementation of the JSF Session Scope within CDI.

  2. javax.faces.bean.SessionScoped (JSR 314) and all other annotations under the javax.faces.bean.* package maintain the JSF-specific dependency injection and bean management mechanism. Beans annotated with JSF annotations however are only useful within the web tier. All the scopes available with JSF annotations have been replicated within the CDI specification.

  3. javax.annotation.ManagedBean (JSR 316) and other DI-related annotations under javax.annotation.* are an attempt to generalize the JSF-based annotations for other uses within the Java EE spec and really shouldn't be used by the end-developer.

Why they exist? Well IMO, the move from JSF beans to CDI beans is a natural evolution of the technology. JSF beans have had a good run but the likes of Spring, Guice and Seam made it obvious that the technology was not sufficient. There was also a need to bridge the gap between the web components and EJBs, and the response to that need is CDI.

See these related questions too: