Spring AOP Tutorial

In this Spring AOP tutorial, learn what aspect-oriented programming is with examples. Also learn what advice, join-point, and point-cut expressions are and how to use them in a Spring application.

1. What is Spring AOP?

Spring AOP enables Aspect-Oriented Programming in spring applications. In AOP, aspects enable the modularization of concerns such as transaction management, logging or security that cut across multiple types and objects (often termed crosscutting concerns).

AOP provides a way to dynamically add the cross-cutting concern before, after or around the actual logic using simple pluggable configurations. It also makes it easy to maintain code in the present and future. You can add/remove concerns without recompiling complete source code simply by changing configuration files (if you are applying aspects using XML configuration).

2. What is advice, joinpoint or pointcut?

  1. An important term in AOP is advice. It is the action taken by an aspect at a particular join-point.
  2. Joinpoint is a point of execution of the program, such as executing a method or handling an exception. In Spring AOP, a joinpoint always represents a method execution.
  3. Pointcut is a predicate or expression that matches join points.
  4. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut.
  5. Spring uses the AspectJ pointcut expression language by default.
Spring AOP
Spring AOP

3. Types of AOP Advice

There are five types of advice in Spring AOP.

  1. Before advice: Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception).
  2. After returning advice: Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception.
  3. After throwing advice: Advice to be executed if a method exits by throwing an exception.
  4. After advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return).
  5. Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.

4. Spring AOP Example

4.1. Maven Dependencies

Before writing any code, you will need to import Spring AOP dependencies into your project.

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.7.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>5.2.7.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>5.2.7.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.9.5</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.5</version>
</dependency>

Enable AOP configuration in Spring applications.

@Configuration
@EnableAspectJAutoProxy
public class AopConfig {
 
}

4.2. Aspect and pointcut expression

Write aspect class annotated with @Aspect annotation and write point-cut expressions to match joint-point methods.

@Aspect
public class EmployeeCRUDAspect {
      
    @Before("execution(* EmployeeManager.getEmployeeById(..))")     //point-cut expression
    public void logBeforeV1(JoinPoint joinPoint)
    {
        System.out.println("EmployeeCRUDAspect.logBeforeV1() : " + joinPoint.getSignature().getName());
    }
}

4.3. Methods (joint points)

Write methods on which you want to execute advices and those match with point-cut expressions.

@Component
public class EmployeeManager
{
    public EmployeeDTO getEmployeeById(Integer employeeId) {
        System.out.println("Method getEmployeeById() called");
        return new EmployeeDTO();
    }
}

In the above example, logBeforeV1() will be executed before getEmployeeById() method because it matches the join-point expression.

4.4. Run the application

Run the application and watch the console.

public class TestAOP
{
    @SuppressWarnings("resource")
    public static void main(String[] args) {
  
        ApplicationContext context = new ClassPathXmlApplicationContext
                  ("com/howtodoinjava/demo/aop/applicationContext.xml");
 
        EmployeeManager manager = context.getBean(EmployeeManager.class);
  
        manager.getEmployeeById(1);
    }
}

Program output:

EmployeeCRUDAspect.logBeforeV1() : getEmployeeById
Method getEmployeeById() called

Spring aop tutorial for beginners with example.

5. Spring AOP XML Configuration Examples

6. Spring AOP AspectJ Annotations Examples

7. More Spring AOP Tutorial

8. Interview Questions

Happy Learning !!

Spring AOP Doc
AspectJ

Comments are closed for this article!

Comments

4 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.