Spring AOP (Aspect-oriented programming) framework is used to modularize cross-cutting concerns in aspects. Put it simple, it’s just an interceptor to intercept some processes, for example, when a method is execute, Spring AOP can hijack the executing method, and add extra functionality before or after the method execution.
In Spring AOP, 4 type of advices are supported :
- Before advice – Run before the method execution
- After returning advice – Run after the method returns a result
- After throwing advice – Run after the method throws an exception
- Around advice – Run around the method execution, combine all three advices above.
1. Setting up the project structure:
Launch your preferred IDE (I use STS) and Create New Java Project. And then create the file structure as shown below…
You need to download all the JARs that are in User Libraries “aspectJ-lib” and add them to the project’s class path. You can find these JARs here: Spring, Commons-logging, aspectjrt, aspectjweaver.
2. Writing our Logging Aspect:
package com.dineshonjava.sdnext.aop.tutorial.aspectJ; @Aspect public class LoggingAspect { public void loggingAdvice() { System.out.println("Advice run. Get method is called"); } }
3. Configuring Spring AOP and @AspectJ support:
<beans> ..... <bean class="com.dineshonjava.sdnext.aop.tutorial.aspectJ.LoggingAspect" name="loggingAspect"></bean> ..... <aop:aspectj-autoproxy></aop:aspectj-autoproxy> ..... <aop:config> <aop:aspect id="loggingAspect" ref="loggingAspect"> ..... <aop:after method="..." pointcut="..."></aop:after> ..... </aop:aspect> </aop:config> .... </beans>
1. XML Schema based : Aspects are implemented using regular classes along with XML based configuration.
2. @AspectJ based : @AspectJ refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations.
- 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 AspectJ @Before Annotation Advice 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