-1

I wanted to know, is there any option to call a managed bean inside of EJB 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.

Exterminator13
  • 2,152
  • 1
  • 23
  • 28

1 Answers1

3

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. 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.

You should do it the other way round. You should inject the EJB in the managed bean, not the other way round. The EJB should be kept entirely stateless. You should just directly pass the EJB the information it needs as method argument (and never assign it as instance variable of EJB afterwards).

E.g.

@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:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • thanks for your answer. I just wanted to clarify something in your reply: "This is not right" means also "This is not possible at all." ? – Exterminator13 Sep 26 '13 at 11:49
  • I clarified the answer and added a "See also" link which should be good food for read and thought. – BalusC Sep 26 '13 at 11:50
  • OK, I see. As I don't use CDI, the question can be considered as closed. Thank you! – Exterminator13 Sep 26 '13 at 11:53
  • 1
    Even if you used CDI, **you should not do that**. All self respected Java EE developers in the world would bludgeon you. – BalusC Sep 26 '13 at 11:54