I am learning Java EE and JSP. I have created an Enterprise Application project in NetBeans.
I have the EJB project
where all beans are and a WAR project
where all web/client stuff is.
My problem is that the annotation @EJB
does not instantiate my Bean in the WAR application. Can I use @EJB
outside the EJB application?
In the EJB project, I have these files:
CustomerRemote.java
@Remote
public interface CustomerRemote {
public Customer createCustomer();
public Customer getCustomer(int customerId);
public void removeCustomer();
}
CustomerBean.java
@Stateless
public class CustomerBean implements CustomerRemote {
@PersistenceContext(unitName="testPU")
private EntityManager entityManager;
@Override
public Customer createCustomer() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void removeCustomer() {
}
@Override
public Customer getCustomer(int customerId) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
In the WAR project, I have a file that my JSP page uses to communicate with the EJB stuff. The problem is that the CustomerRemote object is never instantiated. @EJB annotation does not seem to work because customerRemote
always is null. But when instantiating it with the lookup
method, it works! So why does not @EJB
work?
public class CustomerProxyBean {
@EJB
private CustomerRemote customerRemote;
public CustomerProxyBean() {
// try {
// InitialContext context = new InitialContext();
// customerRemote = (CustomerRemote)context.lookup("java:app/SimpleShop-ejb/CustomerBean");
//
// } catch (NamingException ex) {
// Logger.getLogger(CustomerProxyBean.class.getName()).log(Level.SEVERE, null, ex);
// }
}
@EJB
annotation will work only in cases where your class is container-managed, that is EJB, servlet, JSP... In your case you put it into plain old Java object (POJO) so injection will not work, as you have experienced. Write your CustomerProxyBean as a stateless session bean, and you'll see the change.
Alternatively, if you want to avoid JNDI for some reason, you can use CDI and @Inject
annotation to inject EJB and achieve wished behaviour, even in POJO:
@Inject
private CustomerRemote customerRemote;