Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between @Named and @ManagedBean annotations in JSF2.0 Tomcat7 [duplicate]

Tags:

This might be a noob question, however in a lot of tutorials and examples I saw these annotations used as if they did the same thing.

However I ran into some limitations using the @Named one (especially with dependency injection etc.) I couldn't find a source where the difference is explained and I'd be very thankful if someone can give a rough overview on when to use one or the other.

like image 465
user871784 Avatar asked Jun 12 '12 09:06

user871784


People also ask

What is managed bean annotation?

bean. ManagedBean) annotation in a class automatically registers that class as a resource with the JavaServer Faces implementation. Such a registered managed bean does not need managed-bean configuration entries in the application configuration resource file.

What is CDI in JSF?

Getting Started with CDI and JSF 2.0Contexts and Dependency Injection (CDI), specified by JSR-299, is an integral part of Java EE 6 and provides an architecture that allows Java EE components such as servlets, enterprise beans, and JavaBeans to exist within the lifecycle of an application with well-defined scopes.

What is a named Bean?

The named bean is a Context and Dependency Injection (CDI) object used in developing a JSF application. After you create a named bean, you can drag it from the Page Data view to use in JSF pages in the project. The named bean is also available through the content assist for EL expressions.


1 Answers

@Named gives a CDI managed bean an EL name to be used in view technologies like JSF or JSP. Note that in a CDI application you don't need the @Named annotation to make a bean managed by CDI (thanks to @Karl for his comment).

@ManagedBean makes the bean managed by JSF and you can:

  • inject it into other @ManagedBean annotated beans (but not into @Named beans!)
  • access it from your views via expression language

See this related question for further information how injection works among both kind of beans.

Note that there is also a difference with the scope of the beans. They come from different packages but are named identically (JSF: javax.faces.bean, CDI: javax.enterprise.context , so it is often a source of error and confusion if you include the wrong class.

From my experience: You should use CDI beans whenever possible since they are more flexible than JSF managed beans. Only drawback is that CDI doesn't know a view scope, so you either need to fall back to @ManagedBean or use some third party extension like Seam.

EDIT: CDI supports ViewScope, more info on LINK

like image 149
Matt Handy Avatar answered Oct 04 '22 13:10

Matt Handy