Over a million developers have joined DZone.

Using @Named vs. @ManagedBean

Determining the best annotations to use for controlling JSF apps using different web containers.

· Java Zone

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

I was looking through some JSF controllers and it was a mix of @Named and @ManagedBean annotations. These annotations provide similar dependency injections, but there are important differences.

Containers

  • @ManagedBean – javax.faces.bean.ManagedBean – managed by JSF container
  • @Named – javax.faces.bean – CDI bean managed by application server

This means @Named beans are visible to the whole JEE container, while @ManagedBean are visible only to the JSF container. The visibility issue is covered in this table:

Inject @Named@ManagedBean
@NamedYY(*)
@ManagedBeanN

Y(*)

* – only if scope of injected bean is broader

One problem is that @Named requires that you use a JEE enabled container – so you have to use TomEE instead of Tomcat.

Scope

A further problem in earlier CDI versions was that there was no CDI equivalent of @ViewScoped. This has now been resolved with  @javax.faces.view.ViewScope.

You also need to be very careful with mixing JSF and CDI as they use different packages – javax.faces.bean vs. javax.enterprise.context.

So What Approach Should You Use?

This is a non-question as from JSF2.3 onwards @ManagedBean is being phased out and the recommended approach is @Named. It is also important not to mix CDI with JSP scopes

However there are circumstances when I would still use @ManagedBean at present:

  • Existing Code is using @ManagedBean – I would stick with @ManagedBean until a migration path is determined
  • Web Container – You just want to use a web container – then sticking with JSF ManagedBeans would be easier

Reference

http://germanescobar.net/2010/04/4-areas-of-possible-confusion-in-jee6.html

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:
java ,jsf ,cdi ,beans ,javabeans

Published at DZone with permission of Martin Farrell, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}