0

我正在尝试在 JSF 上构建一个简单的博客。但是,我不知道如何将相同的有状态 ejb 实例注入 2 个不同的托管 bean。我知道可以通过使用 @ManagedProperty 注释间接完成注入。像这样的东西:

@ManagedBean
@ViewScoped
public class PostController implements Serializable {

private static final long serialVersionUID = 1L;

private Post temporaryPost;

@ManagedProperty(value = "#{authenticationController}")
private AuthenticationController authenticationController;

@Inject
private PostEJB postEJB;

public void save() {
    getTemporaryPost().setAuthor(
            getAuthenticationController().getAuthenticationEJB()
                    .getCurrentSessionUser());
    postEJB.create(getTemporaryPost());
}
    }

我想摆脱

@ManagedProperty(value = "#{authenticationController}") private AuthenticationController authenticationController;

并直接注入AuthenticationEJB,比如

@Inject private AuthenticationEJB authenticationEJB;

所以,而不是

getAuthenticationController().getAuthenticationEJB().getCurrentSessionUser()

我会得到

身份验证EJB.getCurrentSessionUser()

但是,问题是这是新的 authenticationEJB 实例,它不包含当前登录的用户(用户为空)。同时 authenticationController.authenticationEJB.currentsessionuser 包含登录用户。

提前致谢!


终于找到答案了!这很容易:

@ManagedProperty(value = "#{authenticationController.authenticationEJB}")
private AuthenticationEJB authenticationEJB;

现在它指向同一个 authenticationEJB 实例。但是,我相信可能还有其他方法可以做到这一点。

4

1 回答 1

0

好吧,你得到了答案,但也许有几个注释

  • PostController你为什么不直接用@EJB注解注入你的bean呢?
  • 如果您开发一个新项目,CDI beans而不是使用 JSF 托管 Bean,它们很快就会被弃用(整个 Java EE 堆栈正在慢慢转向在任何地方使用 CDI)
  • 然后你可以摆脱@ManagedProperty,每个 bean(基本上是你应用程序中的任何类)都可以通过@Inject注解注入。同样的事情也适用于 EJB,因此 CDI 统一了对大多数类型 bean 的访问。
  • 一些基本的 CDI + JSF 教程在这里
于 2013-10-02T21:16:11.563 回答