3 Simple Enterprise JavaBeans Examples

This chapter describes Java examples of EJBs that use the version 3.x programming model.

This chapter includes the following sections:

Simple Java Examples of 3.x EJBs

The following sections describe simple Java examples of EJBs that use the new metadata annotation programming model. Some procedural sections in this guide that describe how to program an EJB may reference these examples.

Example of a Simple No-interface Stateless EJB

The EJB 3.1 no-interface local client view type simplifies EJB development by providing local session bean access without requiring a separate local business interface, allowing components to have EJB bean class instances directly injected.

The following code shows a simple no-interface view for the ServiceBean stateless session EJB:

package examples;
@Stateless
public class ServiceBean {
  public void sayHelloFromServiceBean() {
    System.out.println("Hello From Service Bean!");
  }
}

The main points to note about the preceding code are:

  • The EJB automatically exposes the no-interface view because no other client views are exposed and its bean class implements clause is empty.

  • The ServiceBean bean file is a plain Java file; it is not required to implement any EJB-specific interface.

  • The class-level @Stateless metadata annotation specifies that the EJB is of type stateless session.

Example of a Simple Business Interface Stateless EJB

The following code shows a simple business interface for the ServiceBean stateless session EJB:

package examples;
/**
* Business interface of the Service stateless session EJB
*/
public interface Service {
  public void sayHelloFromServiceBean();
}

The code shows that the Service business interface has one method, sayHelloFromServiceBean(), that takes no parameters and returns void.

The following code shows the bean file that implements the preceding Service interface; the code in bold is described after the example:

package examples;
import javax.ejb.Stateless;
import javax.interceptor.ExcludeDefaultInterceptors;
/**
 * Bean file that implements the Service business interface.
 * Class uses following EJB 3.x annotations:
 *   - @Stateless - specifies that the EJB is of type stateless session
 *   - @ExcludeDefaultInterceptors - specifies any configured default
 *      interceptors should not be invoked for this class
 */
@Stateless
@ExcludeDefaultInterceptors
public class ServiceBean
  implements Service
{
  public void sayHelloFromServiceBean() {
    System.out.println("Hello From Service Bean!");
  }
}

The main points to note about the preceding code are:

  • Use standard import statements to import the metadata annotations you use in the bean file:

    import javax.ejb.Stateless;
    import javax.interceptor.ExcludeDefaultInterceptors
    

    The annotations that apply only to EJB 3.1 are in the javax.ejb package. Annotations that can be used by other Java EE Version 6 components are in more generic packages, such javax.interceptor or javax.annotation.

  • The ServiceBean bean file is a plain Java file that implements the Service business interface; it is not required to implement any EJB-specific interface. This means that the bean file does not need to implement the lifecycle methods, such as ejbCreate and ejbPassivate, that were required in the 2.x programming model.

  • The class-level @Stateless metadata annotation specifies that the EJB is of type stateless session.

  • The class-level @ExcludeDefaultInterceptors annotation specifies that default interceptors, if any are defined in the ejb-jar.xml deployment descriptor file, should never be invoked for any method invocation of this particular EJB.

Example of a Simple Stateful EJB

The following code shows a simple business interface for the AccountBean stateful session EJB:

package examples;
/**
 * Business interface for the Account stateful session EJB.
 */
public interface Account {
  public void deposit(int amount);
  public void withdraw(int amount);
  public void sayHelloFromAccountBean();
}

The code shows that the Account business interface has three methods, deposit, withdraw, and sayHelloFromAccountBean.

The following code shows the bean file that implements the preceding Account interface; the code in bold is described after the example:

package examples;
import javax.ejb.Stateful;
import javax.ejb.Remote;
import javax.ejb.EJB;
import javax.annotation.PreDestroy;
import javax.interceptor.Interceptors;
import javax.interceptor.ExcludeClassInterceptors;
/**
 * Bean file that implements the Account business interface.
 * Uses the following EJB annotations:
 *    -  @Stateful: specifies that this is a stateful session EJB
 *    -  @Remote - specifies the Remote interface for this EJB
 *    -  @EJB - specifies a dependency on the ServiceBean stateless
 *         session ejb
 *    -  @Interceptors - Specifies that the bean file is associated with an
 *         Interceptor class; by default all business methods invoke the
 *         method in the interceptor class annotated with @AroundInvoke.
 *    -  @ExcludeClassInterceptors - Specifies that the interceptor methods
 *         defined for the bean class should NOT fire for the annotated
 *         method.
 *    -  @PreDestroy - Specifies lifecycle method that is invoked when the
 *         bean is about to be destoryed by EJB container.
 *
 */
@Stateful
@Remote({examples.Account.class})
@Interceptors({examples.AuditInterceptor.class})
public class AccountBean
 implements Account
{
  private int balance = 0;
  @EJB(beanName="ServiceBean")
  private Service service;
  public void deposit(int amount) {
    balance += amount;
    System.out.println("deposited: "+amount+" balance: "+balance);
  }
  public void withdraw(int amount) {
    balance -= amount;
    System.out.println("withdrew: "+amount+" balance: "+balance);
  }
  @ExcludeClassInterceptors
  public void sayHelloFromAccountBean() {
    service.sayHelloFromServiceBean();
  }
  @PreDestroy
  public void preDestroy() {
   System.out.println("Invoking method: preDestroy()");  
  }
}

The main points to note about the preceding code are:

  • Use standard import statements to import the metadata annotations you use in the bean file:

    import javax.ejb.Stateful;
    import javax.ejb.Remote;
    import javax.ejb.EJB;
    
    import javax.annotation.PreDestroy;
    
    import javax.interceptor.Interceptors;
    import javax.interceptor.ExcludeClassInterceptors;
    

    The annotations that apply only to EJB 3.1 are in the javax.ejb package. Annotations that can be used by other Java EE 6 components are in more generic packages, such javax.interceptor or javax.annotation.

  • The AccountBean bean file is a plain Java file that implements the Account business interface; it is not required to implement any EJB-specific interface. This means that the bean file does not need to implement the lifecycle methods, such as ejbCreate and ejbPassivate, that were required in the 2.x programming model.

  • The class-level @Stateful metadata annotation specifies that the EJB is of type stateful session.

  • The class-level @Remote annotation specifies the name of the remote interface of the EJB; in this case it is the same as the business interface, Account.

  • The class-level @Interceptors({examples.AuditInterceptor.class}) annotation specifies the interceptor class that is associated with the bean file. This class typically includes a business method interceptor method, as well as lifecycle callback interceptor methods. See Example of an Interceptor Class for details about this class.

  • The field-level @EJB annotation specifies that the annotated variable, service, is injected with the dependent ServiceBean stateless session bean context. The data type of the injected field, Service, is the business interface of the ServiceBean EJB. The following code in the sayHelloFromAccountBean method shows how to invoke the sayHelloFromServiceBean method of the dependent ServiceBean:

    service.sayHelloFromServiceBean();
    
  • The method-level @ExcludeClassInterceptors annotation specifies that the @AroundInvoke method specified in the associated interceptor class (AuditInterceptor) should not be invoked for the sayHelloFromAccountBean method.

  • The method-level @PreDestroy annotation specifies that the EJB container should invoke the preDestroy method before the container destroys an instance of the AccountBean. This shows how you can specify interceptor methods (for both business methods and lifecycle callbacks) in the bean file itself, in addition to using an associated interceptor class.

Example of an Interceptor Class

The following code shows an example of an interceptor class, specifically the AuditInterceptor class that is referenced by the preceding AccountBean stateful session bean with the @Interceptors({examples.AuditInterceptor.class}) annotation; the code in bold is described after the example:

package examples;
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
import javax.ejb.PostActivate;
import javax.ejb.PrePassivate;
/**
 * Interceptor class.  The interceptor method is annotated with the
 *  @AroundInvoke annotation.
 */
public class AuditInterceptor {
  public AuditInterceptor() {}
  @AroundInvoke
  public Object audit(InvocationContext ic) throws Exception {
    System.out.println("Invoking method: "+ic.getMethod());
    return ic.proceed();
  }
  @PostActivate
  public void postActivate(InvocationContext ic) {
    System.out.println("Invoking method: "+ic.getMethod());
  }
  @PrePassivate
  public void prePassivate(InvocationContext ic) {
    System.out.println("Invoking method: "+ic.getMethod());
  }
}

The main points to notice about the preceding example are:

  • As usual, import the metadata annotations used in the file:

    import javax.interceptor.AroundInvoke;
    import javax.interceptor.InvocationContext;
    import javax.ejb.PostActivate;
    import javax.ejb.PrePassivate;
    
  • The interceptor class is a plain Java class.

  • The class has an empty constructor:

    public AuditInterceptor() {}
    
  • The method-level @AroundInvoke specifies the business method interceptor method. You can use this annotation only once in an interceptor class.

  • The method-level @PostActivate and @PrePassivate annotations specify the methods that the EJB container should call after reactivating and before passivating the bean, respectively.

    Note:

    These lifecycle callback interceptor methods apply only to stateful session beans.

Packaged EJB 3.2 Examples in WebLogic Server

The following sections describe the packaged Java EE 7 examples included with Oracle WebLogic Server, which demonstrate new features in EJB 3.2.

EJB 3.2: Example of Using the Session Bean Lifecyle

This example shows the new session bean lifecycle callback interceptor methods API, including @AroundConstruct and @AroundInvoke.

After you have installed WebLogic Server, the example is in the following directory:

EXAMPLES_HOME/examples/src/examples/javaee7/ejb/lifecylce

EXAMPLES_HOME represents the directory in which the WebLogic Server code examples are configured. See Sample Applications and Code Examples in Understanding Oracle WebLogic Server.

EJB 3.2: Example of a Message-Driven Bean with No-Methods Listener

This example shows how a message-driven bean to implement a listener interface with no methods. A bean that implements a no-methods interface exposes all non-static public methods of the bean class and of any superclasses, except java.lang.Object, as message listener methods.

After you have installed WebLogic Server, the example is in the following directory:

EXAMPLES_HOME/examples/src/examples/javaee7/ejb/no-method-listener

EXAMPLES_HOME represents the directory in which the WebLogic Server code examples are configured. See Sample Applications and Code Examples in Understanding Oracle WebLogic Server.

Packaged EJB 3.1 Examples in WebLogic Server

The following sections describe the packaged Java EE 6 examples included with Oracle WebLogic Server, which demonstrate new features in EJB 3.1.

EJB 3.1: Example of a Singleton Session Bean

This example demonstrates the use of the EJB 3.1 singleton session bean, which provides application developers with a formal programming construct that guarantees a session bean will be instantiated once for an application in a particular Java Virtual Machine (JVM). In this example, a @Singleton session bean provides a central counter service. The Counter EJB is called from a Java client to demonstrate it is being used, with the count being consistently incremented by "1" as the client is invoked multiple times.

After you have installed WebLogic Server, the example is in the following directory:

EXAMPLES_HOME/examples/src/examples/javaee6/ejb/singletonBean

EXAMPLES_HOME represents the directory in which the WebLogic Server code examples are configured. See Sample Applications and Code Examples in Understanding Oracle WebLogic Server.

EJB 3.1: Example of an Asynchronous Method EJB

This example demonstrates the use of the EJB 3.1 asynchronous method invocation. Adding the @Asynchronous annotation to an EJB class or specific method will direct the EJB container to return control immediately to the client when the method is invoked. The method may return a Future object to allow the client to check on the status of the method invocation, and then retrieve result values that are asynchronously produced.

In this example, an @Stateless bean is annotated at the class level, with @Asynchronous indicating its methods are all asynchronous, with each of the methods simulating a long-running calculation. A servlet is used to call the various asynchronous methods, keeping track of the invocation and completion times to demonstrate the asynchronous nature of the method calls.

After you have installed WebLogic Server, the example is in the following directory:

EXAMPLES_HOME/examples/src/examples/javaee6/ejb/asyncMethodOfEJB

EXAMPLES_HOME represents the directory in which the WebLogic Server code examples are configured. See Sample Applications and Code Examples in Understanding Oracle WebLogic Server.

EJB 3.1: Example of a Calendar-based Timer EJB

This example demonstrates the enhanced scheduling capabilities of EJB 3.1. This scheduling functionality takes the form of CRON-styled schedule definitions that can be placed on EJB methods, in order for the methods to be automatically invoked according to the defined schedule. This example shows the use of the @Schedule annotation defined for a method of a @Singleton session bean, which generates and stores the timestamp of when the method was called. A corresponding servlet is provided, into which the TimerBean is injected, which retrieves the list of timestamps to display in a browser.

After you have installed WebLogic Server, the example is in the following directory:

EXAMPLES_HOME/examples/src/examples/javaee6/ejb/calendarStyledTimer

EXAMPLES_HOME represents the directory in which the WebLogic Server code examples are configured. See Sample Applications and Code Examples in Understanding Oracle WebLogic Server.

EJB 3.1: Example of Simplified No-interface Programming and Packaging in a WAR File

This example demonstrates the simplified programming and packaging model changes provided in EJB 3.1. Since the mandatory use of Java interfaces from previous versions has been removed in EJB 3.1, plain-old Java objects can be annotated and used as EJB components. The simplification is further enhanced by the ability to place EJB components directly inside of Web applications, thereby removing the need to produce archives to store the Web and EJB components and combine them together in an enterprise archive (EAR) file.

In this example, a @Stateless annotation is provided on a plain-old Java class that exposes it as an EJB session bean. This is then injected into a @WebServlet class using an @EJB annotation to demonstrate that it is being used as an EJB module. The EJB session bean and servlet classes are then packaged and deployed together in a single WAR file, which demonstrates the simplified packaging and deployment changes available in Java EE 6.

After you have installed WebLogic Server, the example is in the following directory:

EXAMPLES_HOME/examples/src/examples/javaee6/ejb/noInterfaceViewInWAR

EXAMPLES_HOME represents the directory in which the WebLogic Server code examples are configured. See Sample Applications and Code Examples in Understanding Oracle WebLogic Server.

EJB 3.1: Example of Using a Portable Global JNDI Name in an EJB

This example demonstrates the use of the Portable Global JNDI naming option that is available in EJB 3.1. Portable Global JNDI provides a number of common, well-known namespaces in which EJB components can be registered and looked up from using the pattern java:global[/<app-name>]/<module-name>/<bean-name>. This standardizes how and where EJB components are registered in JNDI and how they can be looked up and used by applications. In this example, a servlet is used to look up an EJB session bean using its portable JNDI name java:module/HelloBean.

After you have installed WebLogic Server, the example is in the following directory:

EXAMPLES_HOME/examples/src/examples/javaee6/ejb/portableGlobalJNDIName

EXAMPLES_HOME represents the directory in which the WebLogic Server code examples are configured. See Sample Applications and Code Examples in Understanding Oracle WebLogic Server.

EJB 3.1: Example of Using the Embeddable EJB Container in Java SE

This example demonstrates using the embeddable EJB container available in EJB 3.1, which allows client code and its corresponding enterprise beans to run in a Java SE environment without having to deploy them to a Java EE server.

The example uses the embeddable WebLogic EJB container to view all the user objects being invoked from a Java SE environment. All the user objects are predefined during eager initialization of a singleton component InitBean when the application is started, using the annotations @Startup and @PostConstruct. An instance of EJBContainer is created in the Java client UserClient to look up the session bean reference UserBean and call its business method viewUsers in the application.

After running the example, the client class is executed automatically and prints run-time messages in the command shell in which the example was built. All the existing user objects are retrieved from the samples database and are displayed in detail in the command shell.

After you have installed WebLogic Server, the example is in the following directory:

EXAMPLES_HOME/examples/src/examples/javaee6/ejb/embeddableContainer

EXAMPLES_HOME represents the directory in which the WebLogic Server code examples are configured. See Sample Applications and Code Examples in Understanding Oracle WebLogic Server.

EJB 3.0: Example of Invoking an Entity From A Session Bean

For an example of invoking an entity from a session bean, see the EJB 3.0 example in the distribution kit. After you have installed WebLogic Server, the example is in the following directory:

EXAMPLES_HOME/examples/src/examples/ejb/ejb30

EXAMPLES_HOME represents the directory in which the WebLogic Server code examples are configured. See Sample Applications and Code Examples in Understanding Oracle WebLogic Server.