O'Reilly logo

AspectJ Cookbook by Russ Miles

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

22.2. Applying Transactions

Problem

You want to introduce transactional behavior to a method in your application.

Solution

Use the Director aspect-oriented design pattern to declare an abstract aspect that captures the generic behavior of controlling a transaction, as shown in Example 22-4. Extending the abstract transaction aspect, declare specialized subaspects for each transaction within your application.

Example 22-4. Declaring the generic behavior of a transaction in a reusable abstract aspect

public abstract aspect TransactionAspect 
{
   protected abstract pointcut transactionalCall( );
   
   protected pointcut transactionBoundary( ) : 
      transactionalCall( ) && !cflowbelow(transactionalCall( ));
   
   protected interface Transaction
   {
      public void commit( );
      public void rollback( );
   }
   
   protected Transaction transaction;

   before( ) : transactionBoundary( ) 
   { 
      setupTransaction(thisJoinPoint.getArgs( ));
   }
   
   after( ) returning: transactionBoundary( ) 
   { 
      transaction.commit( );
   }
   
   after( ) throwing: transactionBoundary( ) 
   { 
      transaction.rollback( );  
   }
   
   protected abstract void setupTransaction(Object[] args);
}

Discussion

Transactions are used to group a selection of operations into a cohesive unit that either completes or, in the case where one step in the process fails, reverts back to its original state.

In Example 22-4, the TransactionAspect first specifies the transactionCall( ) abstract pointcut. This pointcut is used by specialized subaspects to specify the methods within the target application that are ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required