EJB 3 (@Session) For Absolute Beginners - 3 Minutes Bootstrap, 5 Steps 📎
Requirements:
- Installled JDK 1.5 (better 1.6)
- An IDE of your choice e.g. vi, emacs, netbeans 6.1 (SE or EE), Eclipse Genymede (SE or EE)
- @Stateless, @Local Annotations in classpath
- An Java EE 5 capable application server of your choice. It will work with Glassfish v1+ (better v2), JBoss 4.2+, WLS 10+ and probably Geronimo (not tried yed)
What is to do:
- In the IDE you will have to point to a JAR containing the two annotations. If you have the Reference Implementation installed (Glassfish), put just: glassfish\lib\javaee.jar to the classpath. IDEs with built in EE support have already everything you need. However for the very first time I would prefer to develop "from scratch" an EJB.
- Create an interface with a method (without a method is a little bit odd :-)):
import javax.ejb.Remote;
@Remote
public interface HelloWorld {
public void sayHello();
} - Create a class which implements this interface. You will be forced by a good IDE (probly not by vi or emacs) to implement this interface:
import javax.ejb.Stateless;
@Stateless
public class HelloWorldBean implements HelloWorld {
public void sayHello() {
System.out.println("Hello!");
}
} - Compile everything and JAR the output (in Netbeans just "build", in Eclipse "Export -> JAR")
- Copy the JAR into the autodeploy folder of WLS 10 (bea10\user_projects\domains\YOUR_DOMAIN\autodeploy), or glassfish\domains\domain1\autodeploy in the case of Glassfish v2, or jboss-4.2.2.GA\server\default\deploy in case of JBoss
- Inspect the log files, you are done :-)
What you have gained:
- It's threadsafe (in multicore environments as well)
- Remoting: you can access the interface remotely
- It's transactional - transactions are started for you
- It's pooled - you can control the concurrency and prevent "denial of service" attacks.
- It's monitored: and EJB have to be visible through JMX. Application servers provide additional monitoring services as well.
- Dependency Injection just works - you can inject persistence, other beans, legacy pojos (I will cover this in some upcomings posts)
- It's portalble and so vendor-neutral. Deployment to different application servers just works
- There is NO XML.
- Its easily accessible (via DI), from Restful services, JSF, Servlets etc.
- Clustering and security are beneficial as well - but not the main reason to use EJBs