java将实体注入到ViewScope Bean中
我是CDI新手,希望将其用于JSF2应用程序。类MyUser
是一个简单的@Entity
-Bean,在Bean中的@PostConstruct
方法中创建了一个对象:
@Stateful
@Named @javax.faces.bean.SessionScoped
public class UserBean implements Serializable
{
@Named
private MyUser user;
//setter and getter
//@PostConstruct
}
在JSF页面中访问用户就像一个符咒:#{user.lastName}
。但是现在我想从其他bean访问这个对象,例如在这个@ViewScopedBean
:
@Named @javax.faces.bean.ViewScoped
public class TestBean implements Serializable
{
@Inject private MyUser user;
}
我希望当前(登录的)MyUser user
可以在其他几个bean中使用,但我不确定如何做到这一点。简单地@Inject
它不起作用(我很确定这对简单的来说有点难)
13:56:22,371 ERROR [org.jboss.kernel.plugins.dependency.AbstractKernelController]
Error installing to Start: name=vfs:///Applications/Development/
jboss-6.0.0.Final/server/default/deploy/test.ear_WeldBootstrapBean state=Create:
org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied
dependencies for type [MyUser] with qualifiers [@Default] at injection
point [[field] @Inject private test.controller.mbean.TestBean.user]
从其他bean访问user
的最佳方法是什么?JSF1。像UserBean bean = (UserBean)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("UserBean");
这样的2样式代码似乎过时了
# 1 楼答案
@injected bean也是@Named bean吗
如果是,MyUser bean的作用域比TestBean小。记住@ViewScoped bean的托管属性必须是@ViewScoped、@SessionScoped或@ApplicationScoped
# 2 楼答案
首先:您不想直接注入实体。实体由ORM框架独立控制,并且有自己的生命周期。不要将它们用作托管bean
详情见here
回答您的问题:您不能“排斥”像(经过身份验证的)用户这样的东西,即使这在Seam 2中是可能的,CDI的整个代理机制也不再允许这样了。您需要执行以下操作:
@LoggedIn
这样的限定符)使用户在应用程序中可用按如下方式注入用户:
这就是CDI的方式;-)
# 3 楼答案
CDI没有指定
@ViewScoped
注释。这是一个JSF2注释。唯一允许的注释是:@RequestScoped
、@SessionScoped
、@ApplicationScoped
、@Dependent
和@ConversationScoped
。前三个是CDI所允许的唯一JSF作用域如果需要支持
@ViewScope
注释,则需要自己编写。幸运的是,someone else has done this before