我对新的 JEE6 CDI 规范有疑问,特别是 @Inject 与 @Named
注释的结合使用,该注释似乎已经取代了 jsf 特定的 @ManagedBean
(用于注册资源)和 @ManagedProperty
(用于注入(inject))注释。
假设您有一个注释为 @ManagedBean @SessionScoped
的 bean 类“User
”,并且使用 @ManagedProperty
将此类的对象注入(inject)到任何 bean 中code> 然后,当创建并注入(inject)该对象时,它也会放入 session 中,我可以访问 session (例如在过滤器中)并使用以下方式检索对象:
User user = (User)((HttpServletRequest) request).getSession().getAttribute("user");
因此,如果我使用 @Named @SessionScoped
尝试相同的逻辑(在 glassfish 3.1.2 中),然后使用 @Inject
我可以确认不存在这样的对象 session 中的 User
类型,但这是我在 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: {}
我哪里做错了?!
最佳答案
如果您使用 @SessionScoped
注释 bean,则基本上将其生命周期绑定(bind)到 HttpSession。这并不意味着 bean 被物理注入(inject)到 session 对象中。
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:
非常重要:不要混合 JSF 和 CDI 注释。将您想要从 JSF 模板中访问的所有 bean 设置为 @Named
,并使用 CDI 的 @Inject
和 @...Scoped
,这就足够了.
回答您的问题:
@SessionScoped
public class User { ... }
@RequestScoped
public class SomeController {
@Inject
User user
...
}
这将在 session 启动时创建User
,并在实例化SomeController
时将其注入(inject)SomeController
(在本例中使用新请求) )。
看看 Weld documentation更完整地开始该主题...
关于java - 从 session 范围检索 @Named 托管 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10182943/