Spring AOP AspectJ @AfterThrowing Annotation Advice Example

In this spring aop after throwing advice example, we will learn how to use aspectj @AfterThrowing annotation with java configuration. In Spring AOP, After Throwing Advice to be executed if a method exits by throwing an exception i.e a method which annotated with AspectJ @AfterThrowing annotation run immediately after any matching pointcut expression method throws any exception. But After throwing Advice does not have the ability to prevent execution flow proceeding to the join point.

Download Application Source Code

Spring AOP AspectJ After Throwing Annotation Advice Example from GitHub.

Let’s create a simple spring application and add logging aspect to be invoked every joint point in the service class in the application. This example is also available with XML configuration in the application Spring AOP AfterThrowing Advice Example.

AspectJ @AfterThrowing Annotation

@AfterThrowing annotation is an Aspectj annotation, it is not Spring AOP annotation, so we have to add Aspectj maven dependency with Spring AOP in this example. Let’s see our LoggingAspect class with after-throwing advice annotation.

 

/**
 * 
 */
package com.doj.aopapp.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * @author Dinesh.Rajput
 *
 */
@Aspect
@Component
public class LoggingAspect {
 
 /**
  * Declaring After Throwing advice 
  * @param jp
  * @throws Throwable
  */
 //@AfterThrowing("execution(* com.doj.aopapp.service.*.*(..))") // After Throwing advice with pointcut expression directly
 @AfterThrowing(pointcut = "logForAllMethods()" , throwing="exc") //After Throwing advice with name pointcut that declared as name logForAllMethods()
 public void afterThrowingAdviceForAllMethods(JoinPoint jp, Exception exc) throws Throwable {
        System.out.println("****LoggingAspect.afterThrowingAdviceForAllMethods() " + jp.getSignature().getName() +" Exception: "+exc);
    }
 
 /**
  * Declaring After Throwing advice for all transfer methods whose taking three arguments of any type 
  * of all classes in the package com.doj.aopapp.service
  * @param jp
  * @throws Throwable
  */
 @AfterThrowing(pointcut = "execution(* com.doj.aopapp.service.*.transfer(*,*,*))", throwing="exc")
 public void afterThrowingAdviceForTransferMethods(JoinPoint jp, Exception exc) throws Throwable {
        System.out.println("****LoggingAspect.afterThrowingAdviceForTransferMethods() " + jp.getSignature().getName() +" Exception: "+exc);
    }
 
 /**
  * Declaring named pointcut
  */
 @Pointcut("execution(* com.doj.aopapp.service.*.*(..))")
 public void logForAllMethods(){}
}


@AfterThrowing annotation has throwing attribute and its value must correspond to the name of a parameter in the advice method. When a method execution exits by throwing an exception, the exception will be passed to the advice method as the corresponding argument value.

A throwing attribute also restricts matching to only those method executions that throw an exception of the specified type or parent execption type.

Declare Pointcut expressions

#1. We have declared for after throwing advice, it is valid for all public methods with any number arguments of any type and any return type, for all classes in the com.doj.aopapp.service package.

@AfterThrowing(pointcut = "logForAllMethods()" , throwing="exc")

#2. We have declared for after throwing advice, it is valid for all public methods whose name is transfer() with taking three arguments of any type and any return type, for all classes in the com.doj.aopapp.service package.

@AfterThrowing(pointcut = "execution(* com.doj.aopapp.service.*.transfer(*,*,*))", throwing="exc")

Spring AOP AspectJ @AfterThrowing Annotation Example

Now let’s see complete example of Spring AOP aspectj @AfterThrowing annotation.

Spring AOP and AspectJ Maven Dependencies

<properties>
   <spring.version>4.3.7.RELEASE</spring.version>
   <aspectj.version>1.8.9</aspectj.version>
  </properties>
  
  <dependencies>
   <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context</artifactId>
         <version>${spring.version}</version>
     </dependency>
     <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context-support</artifactId>
         <version>${spring.version}</version>
     </dependency>
     <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-aop</artifactId>
         <version>${spring.version}</version>
     </dependency>
     
     <dependency>
          <groupId>org.aspectj</groupId>
          <artifactId>aspectjrt</artifactId>
          <version>${aspectj.version}</version>
      </dependency>
      <dependency>
          <groupId>org.aspectj</groupId>
          <artifactId>aspectjweaver</artifactId>
          <version>${aspectj.version}</version>
      </dependency>
  </dependencies>

ApplicationContext Configuration file based on Java Config

AppConfig.java

/**
 * 
 */
package com.doj.aopapp.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

/**
 * @author Dinesh.Rajput
 *
 */
@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages={"com.doj.aopapp.aspect", "com.doj.aopapp.service"})
public class AppConfig {
 
}

#1. Enabling @AspectJ using @EnableAspectJAutoProxy Annotation:

Spring AOP provides an annotation to enable @AspectJ support in the application. By default spring framework doesn’t create any proxy for any advice, so we have to enable by using @EnableAspectJAutoProxy annotation.

@Configuration
@EnableAspectJAutoProxy
public class AppConfig {

}

#2. Enabling @AspectJ using <aop:aspectj-autoproxy/> in XML Configuration:

<aop:aspectj-autoproxy/> namespace is equivalent to @EnableAspectJAutoProxy annotation to enable @AspectJ support in the application in XML configuration. Let’s see how to use this namespace <aop:aspectj-autoproxy/>.

<!-- Enable @AspectJ annotation support  -->
    <aop:aspectj-autoproxy/>

Target method of Service class on which aspects needs to apply

TransferService.java

/**
 * 
 */
package com.doj.aopapp.service;

/**
 * @author Dinesh.Rajput
 *    
 */
public interface TransferService {
 
 void transfer(String accountA, String accountB, Long amount);
 
 Double checkBalance(String account);
 
 Long withdrawal(String account, Long amount);
 
 void diposite(String account, Long amount);
}

/**
 * 
 */
package com.doj.aopapp.service;

import org.springframework.stereotype.Service;

/**
 * @author Dinesh.Rajput
 *
 */
@Service
public class TransferServiceImpl implements TransferService {

 @Override
 public void transfer(String accountA, String accountB, Long amount) {
  System.out.println(amount+" Amount trasferring from "+accountA+" to "+accountB);
  throw new NullPointerException("Opps something went wrong!!!");
 }

 @Override
 public Double checkBalance(String account) {
  System.out.println("Available balance: 50000");
  return new Double(50000);
 }

 @Override
 public Long withdrawal(String account, Long amount) {
  System.out.println("Withdrawal amount: " +amount);
  return amount;
 }

 @Override
 public void diposite(String account, Long amount) {
  System.out.println(amount+" Amount has been diposited to "+account);
 }

}

Aspect class:
LoggingAspect.java as given above in this tutorial.

Test Class for Spring AspectJ Configuration and Execution

Let’s execute following test class and analyse the output on the console.

/**
 * 
 */
package com.doj.aopapp.test;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.doj.aopapp.config.AppConfig;
import com.doj.aopapp.service.TransferService;

/**
 * @author Dinesh.Rajput
 *
 */
public class Main {

 /**
  * @param args
  */
 public static void main(String[] args) {
  ConfigurableApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
  TransferService transferService = applicationContext.getBean(TransferService.class);
  transferService.checkBalance("accountA");
  transferService.transfer("accountA", "accountB", 50000l);
  transferService.diposite("accountA",  50000l);
  transferService.withdrawal("accountB", 40000l);
  applicationContext.close();
 }

}

Output on the Console:

Mar 09, 2017 9:33:29 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6576fe71: startup date [Thu Mar 09 21:33:29 IST 2017]; root of context hierarchy
Available balance: 50000
50000 Amount trasferring from accountA to accountB
****LoggingAspect.afterThrowingAdviceForAllMethods() transfer Exception: java.lang.NullPointerException: Opps something went wrong!!!
****LoggingAspect.afterThrowingAdviceForTransferMethods() transfer Exception: java.lang.NullPointerException: Opps something went wrong!!!
Exception in thread “main” java.lang.NullPointerException: Opps something went wrong!!!
at com.doj.aopapp.service.TransferServiceImpl.transfer(TransferServiceImpl.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:62)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:62)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy15.transfer(Unknown Source)
at com.doj.aopapp.test.Main.main(Main.java:25)

As output of above console, every log messages has been executed when target method (transfer) is throwing exception in execution and terminate by error log and other method (checkBalance) executed normally without any exception so other matching pointcut expressions are not executed this target method.

Project Structure

Spring AOP AspectJ @AfterThrowing Annotation Advice Example

 

Spring AOP Related Posts

 

Previous
Next