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

1

25

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.

Riddell answered 12/6, 2012 at 9:48 Comment(1)
What kind of limitations? @ManagedBean is a subset of the functions of @Named, so @Named should work everywhere.Decca
D
43

@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

Direct answered 12/6, 2012 at 10:35 Comment(6)
+1. @matt: I think RequestScoped + KeepAlive = ViewScoped so that can be also be used with @Named. Am i correct?Centrepiece
@Abhinav: KeepAlive from some component library like Richfaces?Direct
@matt: yes in richfaces3.3.3 along with JSF2.0 I am using keepalive along with request scope.Centrepiece
@MattHandy Regarding the bean and Named I think you are a bit misleading. The bean is already managed by cdi and can be injected etc. Your description sounds more like Name from Seam 2. Named is for EL. Please correct me if I am wrongCapsize
@MattHandy Looks really nice now and upvoted. For someone who wants viewScope Deltaspike will provide it in the next release 04-incubating and until then several great scopes can be found Myfaces CODI. Seam has a nice scope as well in RenderScoped iircCapsize
Now you can use viewScope for CDI bean natively by importing javax.faces.view.ViewScoped. #14384869Attrahent

© 2022 - 2024 — McMap. All rights reserved.