Spring AOP AspectJ @After Annotation Example

This Spring AOP tutorial will teach us to use AspectJ @After annotation. The @After annotation is applied to a method within an aspect that should be executed after the advised method has been executed.

In this tutorial, we will create a simple Spring application, add a logging aspect, and then invoke aspect methods based on pointcuts information passed in @After annotation.

1. AspectJ @After Annotation Usage

We can use @After annotation in the manner below. In the following example, the logAfterAllMethods() method is annotated with @After, indicating that it should be executed after the methods that match the specified pointcut expression.

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggingAspect {

  private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);

  @After("execution(* com.howtodoinjava.core.aop.service.EmployeeService.*(..))")
  public void logAfterAllMethods(JoinPoint joinPoint) {
    logger.info("LoggingAspect: Logging after aspect execution");
  }
}

The equivalent XML configuration is:

<!-- Enable AspectJ auto proxy -->
<aop:aspectj-autoproxy />

<!-- Define the aspect -->
<bean id="loggingAspect" class="com.example.aspect.LoggingAspect" />

<!-- Configure the aspect and pointcut -->
<aop:config>
    <aop:aspect id="afterAspect" ref="loggingAspect">
        <aop:pointcut id="afterPointcut"
                      expression="execution(* com.howtodoinjava.core.aop.service.EmployeeService.*(..))" />
        <aop:after method="logAfterAllMethods" pointcut-ref="afterPointcut" />
    </aop:aspect>
</aop:config>

2. Advised Method throws an Exception

When the advised method throws an exception, the @After annotated method still runs. This ensures that the cleanup or logging activities specified in the @After advice can still be performed even when an exception is thrown in the advised method.

It is worth mentioning that if we have an additional @AfterThrowing annotated method and the advised method throws an exception, both advices will be executed. The @AfterThrowing advice will receive the exception as a parameter.

@After("execution(* com.example.service.*.*(..))")
public void logAfter() {
    // This advice will be executed after the target method, regardless of exceptions.
}

@AfterThrowing(pointcut = "execution(* com.example.service.*.*(..))", throwing = "ex")
public void handleException(Exception ex) {
    // This advice will be executed if an exception occurs.
}

3. Demo

When we run any method in the class com.howtodoinjava.core.aop.service.EmployeeService then we can see that the logAfterAllMethods() is executed after it is completed.

import com.howtodoinjava.core.demo.beans.Employee;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class EmployeeService {

  private static final Logger logger = LoggerFactory.getLogger(EmployeeService.class);

  public Employee save(Employee employee) {
    logger.info("Saving the Employee...");
    return null;
  }
}

Let’s run a method and verify the output.

import com.howtodoinjava.core.aop.service.EmployeeService;
import com.howtodoinjava.core.demo.beans.Employee;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {

  public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

    EmployeeService employeeService = context.getBean(EmployeeService.class);
    employeeService.save(new Employee());

    context.close();
  }
}

The program output is:

2023-11-27T12:07:49.261+0530 INFO Saving the Employee...
2023-11-27T12:25:13.092+0530 INFO LoggingAspect: Logging after aspect execution

4. Maven

To get the @After annotation working, we need to ensure that Spring AOP is setup correctly. So make sure we have the following dependencies:

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>6.1.1</version>
</dependency>

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-aop</artifactId>
  <version>6.1.1</version>
</dependency>

<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjweaver</artifactId>
  <version>1.9.20</version>
</dependency>

5. Enabling AOP

Also, we must enable the AOP support to @Aspect annotation to work.

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@EnableAspectJAutoProxy
@ComponentScan
public class AppConfig {
  //...
}

6. Conclusion

The @After annotation in Spring AOP with AspectJ is an way method for executing tasks after method completion such as cleanup activities, logging, or any other post-execution operations.

Happy Learning !!

Soure Code on Github

Comments

Subscribe
Notify of
guest
0 Comments
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.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode