i've a question about the new JEE6 CDI specification, in particular the use of @Inject in conjunction with @Named
annotations that seems to have replaced the jsf specific @ManagedBean
(for register resource) and @ManagedProperty
(for injection) annotations.
Assuming you have a bean class " User
" annotated @ManagedBean @SessionScoped
and an object of this class is injected in any bean using @ManagedProperty
then when this object is created and injected it is also put in session and i could access the session (for example in a filter) and retrieve object using:
User user = (User)((HttpServletRequest) request).getSession().getAttribute("user");
So, if I try the same logic (in glassfish 3.1.2) using @Named @SessionScoped
and then @Inject
I can confirm that there is no such object of type User
in session, but this is what i find in session:
attribute_name: org.jboss.weld.context.conversation.ConversationIdGenerator attribute_value: org.jboss.weld.context.conversation.ConversationIdGenerator@b374765 attribute_name: org.jboss.weld.context.ConversationContext.conversations attribute_value: {}
where i'm doing wrong?!
If you annotate a bean with @SessionScoped
, you are basically binding its lifecycle to the HttpSession. This does not mean that the bean is physically injected into the session-object.
Assuming you have a bean class "User" annotated @ManagedBean @SessionScoped and an object of this class is injected in any bean using @ManagedProperty then when this object is created and injected it is also put in session and i could access the session (for example in a filter) and retrieve object using:
Very important: don't mix JSF and CDI annotations. Make all beans you want to access from within a JSF template @Named
, and use CDI's @Inject
and @...Scoped
, that's sufficient.
To answer your question:
@SessionScoped
public class User { ... }
@RequestScoped
public class SomeController {
@Inject
User user
...
}
This will create User
when the session starts and inject it into SomeController
when SomeController
is instantiated (with a new request, in this example).
Have a look at the Weld documentation to get a more complete start with that topic...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.