Skip Headers
Oracle® Fusion Middleware Programming Enterprise JavaBeans for Oracle WebLogic Server
12c Release 1 (12.1.1)

Part Number E24972-02
Go to Documentation Home
Home
Go to Table of Contents
Contents
Go to Feedback page
Contact Us

Go to previous page
Previous
Go to next page
Next
PDF · Mobi · ePub

3 Simple Enterprise JavaBeans Examples

The following sections describe Java examples of EJBs that use the version 3.x programming model:

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.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:

WL_HOME/samples/server/examples/src/examples/javaee6/ejb/singletonBean

WL_HOME refers to the directory in which you installed WebLogic Server, such as /Oracle/Middleware/wlserver_12.1.

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:

WL_HOME/samples/server/examples/src/examples/javaee6/ejb/asyncMethodOfEJB

WL_HOME refers to the directory in which you installed WebLogic Server, such as /Oracle/Middleware/wlserver_12.1.

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:

WL_HOME/samples/server/examples/src/examples/javaee6/ejb/calendarStyledTimer

WL_HOME refers to the directory in which you installed WebLogic Server, such as /Oracle/Middleware/wlserver_12.1.

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 the example, an @Stateless annotation is provided on a plain old Java class that exposes it as an EJB session bean. This is then injected into an @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:

WL_HOME/samples/server/examples/src/examples/javaee6/ejb/noInterfaceViewInWAR

WL_HOME refers to the directory in which you installed WebLogic Server, such as /Oracle/Middleware/wlserver_12.1.

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:

WL_HOME/samples/server/examples/src/examples/javaee6/ejb/portableGlobalJNDIName

WL_HOME refers to the directory in which you installed WebLogic Server, such as /Oracle/Middleware/wlserver_12.1.

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:

WL_HOME/samples/server/examples/src/examples/ejb/ejb30

WL_HOME refers to the directory in which you installed WebLogic Server, such as /Oracle/Middleware/wlserver_12.1.