Difference between @Named and @ManagedBean annotat

2019-01-07 09:43发布

This question already has an answer here:

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.

1条回答
不美不萌又怎样
2楼-- · 2019-01-07 10:44

@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.

查看更多
登录 后发表回答