About Me

My photo
I know the last digit of PI

Friday, May 08, 2015

Glassfish 2.1: Using Local EJB interface in WAR's POJO

Base interface for local and remote interfaces

public interface HelloEjb extends Serializable {
  public String hello(); 
}

Define local interface

@Local
public interface HelloEjbLocal extends HelloEjb {
}

Define remote interface

@Remote
public interface HelloEjbRemote extends HelloEjb {
}

Define EJB implementation

//@Local(HelloEjbLocal.class) // not needed
//@Remote(HelloEjbRemote.class) // not needed
@Stateless
public class HelloEjbImpl extends HelloEjbLocal, HelloEjbRemote {
  public String hello() { return "hello world!"; }
}

Using EJB in POJO

Please note that the POJO must be called from a class that is part of the WAR (either servlet, webservice, etc.)
// Notes: POJO must be called by class from the WAR
@EJB(name="helloEjbJndi", beanInterface=HelloEjbLocal.class)
public class HelloClient {

  public HelloEjb getEjb() throws NamingException {
    final InitialContext ctx = new InitialContext();
    return (HelloEjb)ctx.lookup("java:comp/env/helloEjbJndi");
  }
}