Starting With EJB 3

I’m currently studying to take SCEA, so, even after so long time after the EJB3 specification was released I took my first look into it only now.  For sure, one of the most important change was the simple way to develop our EJB components, now POJO based with annotations, so, we can be away from the XML configuration as maximum as possible.

To run this example I used:

-          Glassfish V2

-          Eclipse Ganymede

-          JDK 1.6

To install the glassfish server you can follow the steps given on glassfish site. To make the development easier I added the glassfish plugin to eclipse, so easily we can run our application. It can be added in when we are adding the server runtime, we have a option called “Download additional adapters”.

Once you add the plugin for glassfish we can start developing our first EJB3.

For this we create a new EJB Project on eclipse, it will ask for a project name and target Runtime, for target runtime choose Glassfish V2.1.

Once we create our project let us create our remote interface, it will be like this:

And our SessionBean, it will be a stateless session bean. This class needs only to add the annotation @Stateless to indicate that it is a Stateless Session Bean and implements the Remote interface with its methods, in our example only one method.

Now, to make our EJB available in the glassfish server we only need to do this:

Right Button over the project-> Run as.. -> Run on Server

Choose the glassfish server and associate your project to it and then click Run.

For this case, it will do nothing, it will just deploy the EJB in the server.

To make sure that your EJB was deployed:

Now lets us a make a Web Application to consume our Ejb service

Create new Dynamic Web Project, select glassfish as target runtime.

Create a jar from your Ejb Project. Add it to the web project lib folder.

Create a new Servlet. The Code of the servlet will be like this:

From this image we can see that we refer to our EJB, only by its Remote interface annotated with @EJB, with this glassfish will care about the depency injection and will inject the EJB reference to be used by the servlet.

To test, run the web application: Run as… -> Run on Server

And acess your servlet.

If everything was ok, you will see a screen like this:

As we could see, with EJB3 the development of Business Components became very simple and fast.

That’s it.

Thanks, Junior