Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why @ManagedBean works while @Named doesn't?

 
Mellon Sun
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am reading the book Core Java Server Faces 3rd Edition.
There is a sample of JSF ajax feature and I tried it with NetBeans9.1 and GlassFish V3.
However only when I use @ManagedBean, it works well. If I use @Named annotation, it seems that the @SessionScoped annotation doesn't work.
Because I saw that the default constructor of User bean was called four times when I click the Login button and the getGreeting() cannot catch the filed "name"'s value.



 
Mellon Sun
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I use @ManagedBean everything is ok:


When I use @Named instead, it is not ok anymore:



too many times the constructor method was called in each request.
 
Ilari Moilanen
Ranch Hand
Posts: 199
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I might be on the wrong track here but here goes

Perhaps you use the same @SessionScoped annotation on both cases? Does the example you use do the same thing?

I have understood that if you use the @Named annotation (and are using the J2EE CDI (Contexts and Dependency Injection)) you should use the annotation used with enterprise beans i.e.
@javax.enterprise.context.SessionScoped

and if you use the @ManagedBean annotation (that is a JSF thing and not a "J2EE wide annotation") you use the JSF annotation meant for JSF beans i.e.
@javax.faces.bean.SessionScoped
 
Tim Holloway
Saloon Keeper
Pie
Posts: 18152
52
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@ManagedBean is a JSF annotation and it wires itself into the faces-config. @Named is not. Although I believe that @Named can be used to set the management name of the bean instance, it doesn't inherently wire in to the JSF bean management subsystem.
 
Carlos Jorge Tavares Ferreira
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I had the same issue and the @Named annotation started working correctly after I've included an empty beans.xml file under WEB-INF. Now I just use the @Named annotation and don't use @ManagedBean no longer.
 
Mellon Sun
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I use NetBeans IDE, so a beans.xml was automatically included in WEB-INF directory. I guess this is not the point.
I tried to replace the import declaration of SessionScope from javax.faces.bean.SessionScoped to javax.enterprise.context.SessionScoped and it worked.

Thanks for your help.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic