Pages

Tuesday, June 29, 2010

Simple EJB3 Example

This post provides instructions on creating a simple Stateless Session Bean and a test client to see it working. It assumes Eclipase IDE and JBoss.

Create a new EJB project in Eclipse, called EJB3SessionBeanExample. Accept all project defaults.

Create 2 packages under the ejbModule directory: "bean" and "client"

Create the following classes under the bean folder:

IHelloBean

package bean;

import java.io.Serializable;

public interface IHelloBean extends Serializable {
  public void doSomething();
}

HelloBeanRemote

package bean;
import javax.ejb.Remote;

@Remote
public interface HelloBeanRemote extends IHelloBean {

}

HelloBeanLocal

package bean;
import javax.ejb.Local;

@Local
public interface HelloBeanLocal extends IHelloBean {

}

HelloBean

package bean;

import javax.ejb.Stateless;

/**
* Session Bean implementation class
*/
@Stateless
public class HelloBean implements HelloBeanRemote, HelloBeanLocal {

  private static final long serialVersionUID = 9184424076718418234L;
  public void doSomething() {
    System.out.println("Hello World!");
  }
}

Create the HelloBeanClient under the client folder:

package client;

import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class HelloBeanClient {
  public static void main(String[] args) {
    try {
      Properties props = new Properties();
      props.setProperty("java.naming.factory.initial",
          "org.jnp.interfaces.NamingContextFactory");
      props.setProperty("java.naming.factory.url.pkgs",           "org.jboss.naming");
      props.setProperty("java.naming.provider.url",
"127.0.0.1:1099");

      InitialContext ctx = new InitialContext(props);
      MyBeanRemote bean = (MyBeanRemote) ctx.lookup("MyBean/remote");

      bean.doSomething();
    } catch (NamingException e) {
      e.printStackTrace();
    }
  }
}

Right click on the EJB3SessionBeanExample project and select Run As -> Run on Server to publish to the server.

Once it is successfully deployed, right click on the HelloBeanClient class and select Run As -> Java Application. Accept any defaults and run it. You should see Hello World! printed to the console (or log C:\Apps\JBoss\jboss-5.1.0.GA\server\default\log depending on setup).

0 comments:

Post a Comment

 
Powered by Blogger