EJB 3: From legacy technology to secret weapon

Four factors that streamline and modernize EJB 3 development

1 2 3 4 5 6 Page 2
Page 2 of 6

Convention over configuration, or configuration by exception

The principle of convention over configuration is simple: suitable convention is preferable to fine-grained configuration. (The EJB 3 Expert Group didn't invent convention over configuration, by the way; it borrowed it from Ruby on Rails.) But convention alone is not enough. Essential information, such as the name of the class, is still needed, but it's derived from the class itself using reflection and doesn't need to be configured. This is the main difference between EJB 3 and Java 2 Enterprise Edition (J2EE) and other frameworks from its era: With EJB 3, plain classes with only a few annotations have replaced huge deployment descriptors and XML configuration.


A subset of the information stored in EJB 2.1 deployment descriptors is available now as Java 5 annotations. The EJB 3.x and JPA specifications rely heavily on them. Annotations are supplemented by metadata derived via reflection from the bytecode and by suitable defaults. The introduction of annotations has dramatically improved the metadata's usability. Now the compiler checks for the availability of default values and for correct typing, so you needn't rely on the Javadoc and the deployment process to implement correct syntax. No additional tools or specific IDE extensions are necessary for this purpose.

The annotations introduced with Java EE 5 are lean and explicit. You just "mark" an ordinary Java class (a plain old Java object, or POJO) with the @Stateless annotation to make it an EJB, as in Listing 3.

Listing 3. EJB 3 annotated POJO

public class HelloBean {

The container recognizes HelloBean as a stateless session bean and applies behavior -- transactions, state, security aspects, and remoting -- that it derives from conventions or that you configure.

I've explicitly configured HelloBean's stateless nature with the @Stateless annotation. But you do not need to configure transactions explicitly. The default @TransactionAttribute(TransactionAttributeType.REQUIRED) annotation is also applied, although it wasn't specified. In the default case, every method in a transaction is executed. If a transaction is already active, it is reused; if no transaction exists yet, it is started for you. You can specify this annotation explicitly, override the default with another setting, or rely on the default.

Even the implementation of the interface is no longer needed. All public methods are automatically exposed to the client (the bean's user). The client acquires an instance of the bean not via a Java Naming and Directory Interface (JNDI) lookup, but using dependency injection.

1 2 3 4 5 6 Page 2
Page 2 of 6