In this spring aop after advice example, we will discuss how to use aspectj @After annotation with java configuration in the application. In Spring AOP After Advice is that executes just after a join point i.e a method which annotated with AspectJ @After annotation run just after the all methods matching with pointcut expression. But After Advice does not have the ability to prevent execution flow proceeding to the join point.
Let’s create a simple spring application and add logging aspect to be invoked every joint point in the service class in the application. In this example, We will create simple spring application, add logging aspect and then invoke aspect methods based on pointcuts information passed in @After annotation. This example is also available with XML configuration in the application Spring AOP After Advice Example.
@After annotation is not a spring annotation, it is aspectj lib annotation so we have to add aspectj maven dependency with spring aop in this example. Let’s see our LoggingAspect class with after advice annotation.
Popular Tutorials
/** * */ package com.doj.aopapp.aspect; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; 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 before advice * @param jp * @throws Throwable */ //@After("execution(* com.doj.aopapp.service.*.*(..))") // after advice with pointcut expression directly @After("logForAllMethods()") //after advice with name pointcut that declared as name logForAllMethods() public void afterAdviceForAllMethods(JoinPoint jp) throws Throwable { System.out.println("****LoggingAspect.afterAdviceForAllMethods() " + jp.getSignature().getName()); } /** * Declaring after 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 */ @After("execution(* com.doj.aopapp.service.*.transfer(*,*,*))") public void afterAdviceForTransferMethods(JoinPoint jp) throws Throwable { System.out.println("****LoggingAspect.afterAdviceForTransferMethods() " + jp.getSignature().getName()); } /** * Declaring named pointcut */ @Pointcut("execution(* com.doj.aopapp.service.*.*(..))") public void logForAllMethods(){} }
#1. In the First pointcut expression, we have declared for after 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.
@After("execution(* com.doj.aopapp.service.*.*(..))")
#2. In the Second pointcut expression, we have declared for after 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.
@After("execution(* com.doj.aopapp.service.*.transfer(*,*,*))")
#3. Named Pointcut
/** * Declaring named pointcut */ @Pointcut("execution(* com.doj.aopapp.service.*.*(..))") public void logForAllMethods(){} @After("logForAllMethods()") //after advice with name pointcut that declared as name logForAllMethods() public void afterAdviceForAllMethods(JoinPoint jp) throws Throwable { System.out.println("****LoggingAspect.afterAdviceForAllMethods() " + jp.getSignature().getName()); }
As above we could also declare named pointcut for complex and repetitive pointcut expressions in the application.
Now let’s see complete example of Spring AOP aspectj @After annotation.
<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>
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. @EnableAspectJAutoProxy Annotation of Spring AOP:
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 enable by using this annotation. In the java configuration we can use this annotation as below in the java configuration file.
@Configuration @EnableAspectJAutoProxy public class AppConfig { }
#2. Enabling @AspectJ Support with XML Configuration:
But in the XML configuration, we have to use namespace which is equivalent to @EnableAspectJAutoProxy annotation to enable @AspectJ support in the application. 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(); } }
As output of above console logs, every log messages has been executed just after target method execution.
Spring AOP Related Posts
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…