Reputation: 406
I have an Ear project, in which I put an EJB project and a simple Web project. I call the EJB in a managedBean and it just works fine with the lookup thing. I call the EJB in the same managedBean and it doesn't instantiate. The web project supports CDI (I checked the support option) Here's the code of the EJB :
@Stateless
@LocalBean
public class MyTestBean implements MyTestBeanRemote, MyTestBeanLocal {
/**
* Default constructor.
*/
public MyTestBean() {
// TODO Auto-generated constructor stub
}
public String message() {
return "This is my Test bean";
}
}
@Local
public interface MyTestBeanLocal {
String message();
}
And here's the code of the calling bean :
@ManagedBean(name="testBean")
public class TestBean {
private String hello = "Hello it is me";
@EJB
private MyTestBeanLocal myTest;
public TestBean() {
hello = myTest.message();
}
}
The "myTest" variable is null. What am I missing?
Upvotes: 2
Views: 1709
Reputation: 3533
You cannot use the injected instance if it is a field injection.
If you want to use the the injected instance in the constructor, you need to do a constructor injection (I'm unsure if EJB supports constructor injection)
@Inject //will only work if you are defining EJB in the same war file
public TestBean(MyTestBeanLocal beanLocal) {
this.beanLocal = beanLocal;
hello = myTest.message();
}
otherwise do whatever you need to do a @postconstruct. This is guaranteed to be called before the bean is put into service.
@PostConstruct
public void postConstruct() {
hello = myTest.message();
}
Upvotes: 2