Question

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.

Was it helpful?

Solution

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:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top