Spring AOP AspectJ @AfterReturning Annotation Advice Example

In this spring aop after returning advice example, we will discuss how to use aspectj @AfterReturning annotation with java configuration in the application. In Spring AOP, After Returning Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception. i.e a method which annotated with AspectJ @AfterReturning annotation run immediately after normally execution of all methods matching with pointcut expression. But After Returning Advice does not have the ability to prevent execution flow proceeding to the join point.

 Download Application Source Code

Spring AOP AspectJ @AfterReturning 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 After-returning Advice Example.

AspectJ @AfterReturning Annotation

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

 

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

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
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 Returning advice 
  * @param jp
  * @throws Throwable
  */
 //@AfterReturning("execution(* com.doj.aopapp.service.*.*(..))") // After Returning advice with pointcut expression directly
 @AfterReturning("logForAllMethods()") //After Returning advice with name pointcut that declared as name logForAllMethods()
 public void afterReturningAdviceForAllMethods(JoinPoint jp) throws Throwable {
        System.out.println("****LoggingAspect.afterReturningAdviceForAllMethods() " + jp.getSignature().getName());
    }
 
 /**
  * Declaring After Returning 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
  */
 @AfterReturning("execution(* com.doj.aopapp.service.*.transfer(*,*,*))")
 public void afterReturningAdviceForTransferMethods(JoinPoint jp) throws Throwable {
        System.out.println("****LoggingAspect.afterReturningAdviceForTransferMethods() " + jp.getSignature().getName());
    }
 
 /**
  * Declaring named pointcut
  */
 @Pointcut("execution(* com.doj.aopapp.service.*.*(..))")
 public void logForAllMethods(){}
}

Declaring Pointcut expressions

#1. We have declared for after returning 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.

@AfterReturning("execution(* com.doj.aopapp.service.*.*(..))")

#2. We have declared for after returning 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.

@AfterReturning("execution(* com.doj.aopapp.service.*.transfer(*,*,*))")

#3. Named Pointcut

/**
 * Declaring named pointcut
 */
@Pointcut("execution(* com.doj.aopapp.service.*.*(..))")
public void logForAllMethods(){}

//After Returning advice with name pointcut that declared as name logForAllMethods()
@AfterReturning("logForAllMethods()") 
public void afterReturningAdviceForAllMethods(JoinPoint jp) throws Throwable {
  System.out.println("****LoggingAspect.afterReturningAdviceForAllMethods() " + jp.getSignature().getName());
}

As mention above, we could also declare named pointcut for removing duplicity of complex and repetitive pointcut expressions in the application.

Spring AOP AspectJ @AfterReturning Annotation Example

Now let’s see complete example of Spring AOP aspectj @AfterReturning 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 namespace 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);
}

TransferServiceImpl.java

/**
 * 
 */
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 has been tranfered from "+accountA+" to "+accountB);
 }

 @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.transfer("accountA", "accountB", 50000l);
  transferService.checkBalance("accountA");
  transferService.diposite("accountA",  50000l);
  transferService.withdrawal("accountB", 40000l);
  applicationContext.close();
 }

}

Output on the Console:

Mar 08, 2017 11:59:17 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6576fe71: startup date [Wed Mar 08 23:59:17 IST 2017]; root of context hierarchy
50000 Amount has been tranfered from accountA to accountB
****LoggingAspect.afterReturningAdviceForAllMethods() transfer
****LoggingAspect.afterReturningAdviceForTransferMethods() transfer
Available balance: 50000
****LoggingAspect.afterReturningAdviceForAllMethods() checkBalance
50000 Amount has been diposited to accountA
****LoggingAspect.afterReturningAdviceForAllMethods() diposite
Withdrawal amount: 40000
****LoggingAspect.afterReturningAdviceForAllMethods() withdrawal
Mar 08, 2017 11:59:18 PM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@6576fe71: startup date [Wed Mar 08 23:59:17 IST 2017]; root of context hierarchy

As output of above console logs, every log messages has been executed just after target method execution.

Project Structure

Spring AOP AspectJ @AfterReturning Annotation Advice Example

 

Spring AOP Related Posts

  1. Spring AOP Interview Questions and Answers
  2. Spring AOP-Introduction to Aspect Oriented Programming
  3. @Aspect Annotation in Spring
  4. Advices in Spring AOP
  5. Spring AOP JoinPoints and Advice Arguments
  6. Spring AOP-Declaring pointcut Expressions with Examples
  7. Spring AOP XML configuration
  8. Spring AOP XML Schema based Example
  9. Spring AOP AspectJ @Before Annotation Advice Example
  10. Spring AOP Before Advice Example using XML Config
  11. Spring AOP AspectJ @After Annotation Advice Example
  12. Spring AOP After Advice Example using XML Config
  13. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  14. Spring AOP After-Returning Advice Example using XML Config
  15. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  16. Spring AOP After Throwing Advice Example using XML Config
  17. Spring AOP AspectJ @Around Annotation Advice Example
  18. Spring AOP Around Advice Example using XML Config
  19. Spring AOP Writing First AspectJ Program in Spring
  20. Spring AOP Proxies in Spring
  21. Spring AOP Transaction Management in Hibernate
  22. Spring Transaction Management
  23. Spring Declarative Transaction Management Example
  24. Spring AOP-Ordering of Aspects with Example
Previous
Next