有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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样式代码似乎过时了


共 (3) 个答案

  1. # 1 楼答案

    @injected bean也是@Named bean吗

    如果是,MyUser bean的作用域比TestBean小。记住@ViewScoped bean的托管属性必须是@ViewScoped、@SessionScoped或@ApplicationScoped

  2. # 2 楼答案

    首先:您不想直接注入实体。实体由ORM框架独立控制,并且有自己的生命周期。不要将它们用作托管bean

    According to this definition, JPA entities are technically managed beans. However, entities have their own special lifecycle, state and identity model and are usually instantiated by JPA or using new. Therefore we don't recommend directly injecting an entity class. We especially recommend against assigning a scope other than @Dependent to an entity class, since JPA is not able to persist injected CDI proxies.

    详情见here

    回答您的问题:您不能“排斥”像(经过身份验证的)用户这样的东西,即使这在Seam 2中是可能的,CDI的整个代理机制也不再允许这样了。您需要执行以下操作:

    • 编写一个托管bean来处理身份验证,并将其放入正确的范围(可能是会话范围)
    • 如果登录成功,则使用此bean的属性来存储经过身份验证的用户
    • 使用producer方法(可能带有像@LoggedIn这样的限定符)使用户在应用程序中可用

    按如下方式注入用户:

    @Inject
    @LoggedIn
    private User user
    

    这就是CDI的方式;-)

  3. # 3 楼答案

    CDI没有指定@ViewScoped注释。这是一个JSF2注释。唯一允许的注释是:@RequestScoped@SessionScoped@ApplicationScoped@Dependent@ConversationScoped。前三个是CDI所允许的唯一JSF作用域

    如果需要支持@ViewScope注释,则需要自己编写。幸运的是,someone else has done this before