Spring AOP Annotation Config Example

One of the key components of Spring is the Aspect-Oriented Programming (AOP) framework. While the Spring IoC container does not depend on AOP, meaning you do not need to use AOP if you don’t want to, AOP complements Spring IoC to provide a very capable middleware solution.

Just like the key unit of modularity in OOP is the class, in AOP the unit of modularity is the aspect. Aspects enable the modularization of concerns (you can read them as cross-cutting concerns as well) such as transaction management that cuts across multiple types and objects.

Spring supports the use of aspects written with AspectJ annotations in its AOP module. Since AspectJ annotations are supported by more and more AOP frameworks, your AspectJ-style aspects are more likely to be reused in other AOP frameworks that support AspectJ.

1. Maven

Here are Maven dependencies that include the required libraries for Spring AOP. Please include the latest versions of these dependencies from the Maven repository.

<dependencies>
    <!-- Spring Core Container -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>6.1.1</version>
    </dependency>

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

    <!-- AspectJ Weaver (for load-time weaving) -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.20</version>
    </dependency>
</dependencies>

2. Enabling AOP Support in Spring

To enable the AOP support in Spring, we need to add the @EnableAspectJAutoProxy annotation in a @Configuration file.

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

@Configuration
@EnableAspectJAutoProxy
@ComponentScan("your.package.name")
public class AppConfig {

    // Additional configuration if needed
}

To enable @AspectJ support with XML-based configuration, use the ‘aop:aspectj-autoproxy‘ element, as the following example shows:

<aop:aspectj-autoproxy/>

Replace ‘your.package.name‘ with the actual package where your application classes are located.

3. Creating an Aspect

Let’s assume we want to create an aspect that logs the method execution time. We’ll use the @Aspect and @Around annotations for this purpose.

The @Aspect annotation indicates that it is an aspect and the @Around annotation specifies the advice type, in this case, around advice. This allows the aspect to perform actions before and after the method execution.

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggerAspect {

    @Around("execution(* your.package.name.*.*(..))")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();

        Object proceed = joinPoint.proceed();

        long endTime = System.currentTimeMillis();
        System.out.println(
            joinPoint.getSignature() + " executed in " + (endTime - startTime) + "ms"
        );

        return proceed;
    }
}

4. Testing the AOP Aspect

To test the AOP configuration and the logging aspect, we will create the application context using AnnotationConfigApplicationContext and then we will invoke a method in the class. When the method execution is intercepted then we can see the output logged in the console indicating its execution time.

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MainApp {

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

        MyService myService = context.getBean(MyService.class);
        myService.performSomeOperation();

        context.close();
    }
}

The program output:

Performing some operation
execution(void your.package.name.MyService.performSomeOperation()) executed in XXXms

This shows that the LoggerAspect has successfully intercepted the method execution and logged the time it took to execute.

We can adjust the package names and method signatures according to the application structure and AOP requirements.

5. Different Types of AOP Advice

Spring AOP provides different types of advice, and each type serves a specific purpose in managing cross-cutting concerns in a Spring application. Here are the main types of AOP advice along with descriptions:

AspectJ AnnotationDescription
@BeforeUsed for before advice. Specifies the method that should be executed before the matched join point.
@AfterReturningUsed for after returning advice. Specifies the method that should be executed after the matched join point successfully returns a result.
@AfterThrowingUsed for after throwing advice. Specifies the method that should be executed after the matched join point throws an exception.
@AfterUsed for after (finally) advice. Specifies the method that should be executed regardless of the outcome of the matched join point (success or exception).
@AroundUsed for around advice. Specifies the method that should be executed to wrap around the matched join point, providing complete control over the method invocation.

These annotations are part of the AspectJ-style AOP in Spring. You can apply them to methods within aspect classes to define the behavior of the advice.

6. Conclusion

In this Spring AOP tutorial, we explored a practical example of Spring AOP using annotation-based configuration. We were able to create a LoggerAspect to log the execution time of methods within our application.

Further, you may learn how AOP integrates with Spring Boot seamlessly, especially with auto-configuration and component scanning.

Happy Learning !!

Soure Code on Github

Comments

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

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode