AspectJ @Before Annotation
@Before annotation is not spring annotation, it is aspectj lib annotation so we have add aspectj maven dependency with spring aop in this application. Let’s see below LoggingAspect class with before advice annotation.
Popular Tutorials
/** * */ package com.doj.aopapp.aspect; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; 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 */ //@Before("execution(* com.doj.aopapp.service.*.*(..))") // before advice with pointcut expression directly @Before("logForAllMethods()") //before advice with named pointcut that declared as name logForAllMethods() public void beforeAdviceForAllMethods(JoinPoint jp) throws Throwable { System.out.println("****LoggingAspect.beforeAdviceForAllMethods() " + jp.getSignature().getName()); } /** * Declaring before 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 */ @Before("execution(* com.doj.aopapp.service.*.transfer(*,*,*))") public void beforeAdviceForTransferMethods(JoinPoint jp) throws Throwable { System.out.println("****LoggingAspect.beforeAdviceForTransferMethods() " + jp.getSignature().getName()); } /** * Declaring named pointcut */ @Pointcut("execution(* com.doj.aopapp.service.*.*(..))") public void logForAllMethods(){} }
Pointcut expressions
1. Following pointcut expression for before advice is valid for all public methods with any arguments of any type and any return type of all classes in the com.doj.aopapp.service package.
@Before("execution(* com.doj.aopapp.service.*.*(..))")
2. Following pointcut expression for before advice is valid for all public methods whose name are transfer() with taking three arguments of any type and any return type of all classes in the com.doj.aopapp.service package.
@Before("execution(* com.doj.aopapp.service.*.transfer(*,*,*))")
Named Pointcut
We can also define pointcut methods for named pointcut. Actually named pointcut is nothing but it is simple way to declaring common pointcut expressions above a method with @Pointcut annotation. This helps to reduce the complexity of writing common complex pointcut expression.
/** * Declaring named pointcut */ @Pointcut("execution(* com.doj.aopapp.service.*.*(..))") public void logForAllMethods(){} /** * before advice with named pointcut that declared as name logForAllMethods() */ @Before("logForAllMethods()") //before advice with name pointcut that declared as name logForAllMethods() public void beforeAdviceForAllMethods(JoinPoint jp) throws Throwable { System.out.println("****LoggingAspect.beforeAdviceForAllMethods() " + jp.getSignature().getName()); }
Spring AOP AspectJ @Before Annotation Example
Now let’s see complete example of Spring AOP aspectj @Before 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 { }
@EnableAspectJAutoProxy in Java Configuration:
This spring aop annotation is used to enable @AspectJ support with Java @Configuration add this @EnableAspectJAutoProxy annotation to the application context file.
@Configuration @EnableAspectJAutoProxy public class AppConfig { }
Enabling @AspectJ Support with XML Configuration:
To enable @AspectJ support with XML based configuration use the <aop:aspectj-autoproxy/> element.
<!-- 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) { return new Double(50000); } @Override public Long withdrawal(String account, Long 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
Now let’s see how to run and what would be output of this application when above configured aspects execute on given pointcut information.
/** * */ 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); System.out.println("Available balance: " +transferService.checkBalance("accountA")); transferService.diposite("accountA", 50000l); System.out.println("Withdrawal amount: " +transferService.withdrawal("accountB", 40000l)); applicationContext.close(); } }
Output on the Console:
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6576fe71: startup date [Tue Mar 07 16:39:17 IST 2017]; root of context hierarchy
****LoggingAspect.beforeAdviceForAllMethods() transfer
****LoggingAspect.beforeAdviceForTransferMethods() transfer
50000 Amount has been tranfered from accountA to accountB
****LoggingAspect.beforeAdviceForAllMethods() checkBalance
Available balance: 50000.0
****LoggingAspect.beforeAdviceForAllMethods() diposite
50000 Amount has been diposited to accountA
****LoggingAspect.beforeAdviceForAllMethods() withdrawal
Withdrawal amount: 40000
Mar 07, 2017 4:39:17 PM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@6576fe71: startup date [Tue Mar 07 16:39:17 IST 2017]; root of context hierarchy
Analyse the output, all join points execute with given information in this example.
Project Structure
Application Source Code
Spring AOP AspectJ @Before Annotation Advice Example on GitHub.
Spring AOP Related Posts
- Spring AOP Interview Questions and Answers
- Spring AOP-Introduction to Aspect Oriented Programming
- @Aspect Annotation in Spring
- Advices in Spring AOP
- Spring AOP JoinPoints and Advice Arguments
- Spring AOP-Declaring pointcut Expressions with Examples
- Spring AOP XML configuration
- Spring AOP XML Schema based Example
- Spring AOP Before Advice Example using XML Config
- Spring AOP AspectJ @After Annotation Advice Example
- Spring AOP After Advice Example using XML Config
- Spring AOP AspectJ @AfterReturning Annotation Advice Example
- Spring AOP After-Returning Advice Example using XML Config
- Spring AOP AspectJ @AfterThrowing Annotation Advice Example
- Spring AOP After Throwing Advice Example using XML Config
- Spring AOP AspectJ @Around Annotation Advice Example
- Spring AOP Around Advice Example using XML Config
- Spring AOP Writing First AspectJ Program in Spring
- Spring AOP Proxies in Spring
- Spring AOP Transaction Management in Hibernate
- Spring Transaction Management
- Spring Declarative Transaction Management Example
- Spring AOP-Ordering of Aspects with Example