简体   繁体   English

如何在无状态EJB bean中调用托管bean?

[英]How to call managed bean inside of stateless EJB bean?

I wanted to know, is there any option to call a managed bean inside of EJB bean. 我想知道,是否可以在EJB bean中调用托管bean。 Imagine, we have the code: 想象一下,我们有以下代码:

@ManagedBean
@SessionScoped
public class MyManagedBean implements Serializable {
  public String getUrl() {
      return "http://www.google.com";
  }
}

@Stateless
public class MyEJB {

  @ManagedProperty(value = "#{myManagedBean}")
  MyManagedBean myManagedBean;

  public void setMyManagedBean(MyManagedBean myManagedBean) {
      this.myManagedBean = myManagedBean;
  }

  public void call() {
      // NullPointerException here
      System.out.println(myManagedBean.getUrl());         
  }
}

I also tried this: 我也试过这个:

@Stateless
public class MyEJB {
  @EJB
  MyManagedBean myManagedBean;
  ...
}

... but it returns different MyManagedBean instance. ...但是它返回不同的MyManagedBean实例。

This is not right. 这是不对的。 With CDI managed beans instead of JSF managed beans it's possible, but it is just not right as in, bad design. 使用CDI托管Bean而不是JSF托管Bean是可行的,但这并不是正确的,糟糕的设计。 The business service should not be aware about the front-end at all. 商业服务完全不应该知道前端。 It makes the business service unreusable on other front-ends than JSF. 它使业务服务在除JSF之外的其他前端上不可重用。

You should do it the other way round. 您应该反过来做。 You should inject the EJB in the managed bean, not the other way round. 您应该将EJB注入托管bean中,而不是相反。 The EJB should be kept entirely stateless. EJB应该保持完全无状态。 You should just directly pass the EJB the information it needs as method argument (and never assign it as instance variable of EJB afterwards). 您应该只将所需的信息作为方法参数直接传递给EJB(然后再不要将其分配为EJB的实例变量)。

Eg 例如

@ManagedBean
@SessionScoped // <-- Did you read https://stackoverflow.com/q/7031885?
public class MyManagedBean implements Serializable {

    private String url = "http://www.google.com";

    @EJB
    private MyEJB myEJB;

    public void submit() {
        myEJB.call(url);
    }

    public String getUrl() {
        return url;
    }

}

and

@Stateless
public class MyEJB {

    public void call(String url) {
        // No NullPointerException here.
        System.out.println(url);
    }

}

See also: 也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM