HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Spring Boot 2 / AOP with Spring Boot

AOP with Spring Boot

Learn to implement AOP in Spring Boot applications and add different aop advices using AspectJ to support cross-cutting concerns, such as logging, profiling, caching, and transaction management.

Table of Contents

1. Setting up AOP with Spring boot
2. Types of Advices
3. Conclusion

Read More : Spring AOP Tutorial

1. Setting up AOP with Spring boot

1.1. Maven

Setting up AOP in spring boot requires including spring-boot-starter-aop dependency. It imports spring-aop and aspectjweaver dependencies into the application. [Starter pom.xml]

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-aop</artifactId>
</dependency>

1.2. Enable/disable auto configuration

Importing above dependencies triggers AopAutoConfiguration which enables AOP using @EnableAspectJAutoProxy annotation.

The auto configuration will NOT be activated if spring.aop.auto = false in application.properties.

#spring.aop.auto = false	//'false' disables the auto configuration

1.3. Creating aspects with @Aspect

An aspect can be created in spring boot with help of annotations @Aspect annotation and registering with bean container with @Component annotation.

Inside the aspect class, we can create advices as required. For example, below class applies around advice on methods inside all classes in package com.howtodoinjava.aop. It captures the method start time and end time, and log the total method execution time in the log file.

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

@Aspect
@Component
public class LoggingAspect 
{
	private static final Logger LOGGER = LogManager.getLogger(LoggingAspect.class);
	
	@Around("execution(* com.howtodoinjava.aop..*(..)))")
    public Object profileAllMethods(ProceedingJoinPoint proceedingJoinPoint) throws Throwable 
    {
        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
         
        //Get intercepted method details
        String className = methodSignature.getDeclaringType().getSimpleName();
        String methodName = methodSignature.getName();
         
        final StopWatch stopWatch = new StopWatch();
         
        //Measure method execution time
        stopWatch.start();
        Object result = proceedingJoinPoint.proceed();
        stopWatch.stop();
 
        //Log method execution time
        LOGGER.info("Execution time of " + className + "." + methodName + " "
        					+ ":: " + stopWatch.getTotalTimeMillis() + " ms");
 
        return result;
    }
}

1.4. Spring boot AOP Example

Create a simple service class to test the above advice.

@Service
public class DomainService 
{
	public Object getDomainObjectById(Long id)
	{
		try {
			Thread.sleep(new Random().nextInt(2000));
		} catch (InterruptedException e) {
			//do some logging
		}
        return id;
    }
}

Create a test class and execute the given method and watch out the logs.

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class AopSpringBootTest 
{
	@Autowired
	private DomainService service;
	
	@Test
	public void testGetDomainObjectById() 
	{
		service.getDomainObjectById(10L);
	}
}
2019-11-07T21:02:58.390+0530 INFO Execution time of DomainService.getDomainObjectById :: 1145 ms

As we can see that AOP advice has been applied over the service method.

2. Types of Advices

There are five types of advice in aspectj AOP.

  1. @Before : 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. @AfterReturning : Advice to be executed after a join point completes normally.
  3. @AfterThrowing : Advice to be executed if a method exits by throwing an exception.
  4. @After : Advice to be executed regardless of the means by which a join point exits (normal or exceptional return).
  5. @Around : Advice that surrounds a join point such as a method invocation.

3. Conclusion

Implementing AOP with Spring boot requires very little effort and we are ready to add aspects as soon as we add spring-boot-starter-aop dependency.

We anytime we want to disable aop auto-configuration, we can easily do by switching to spring.aop.auto to false.

Creating aspects and advices is as simple as adding some annotations e.g. @Aspect, @Around etc.

Happy Learning !!

Sourcecode Download

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

Spring Boot 2 Tutorial

  • Spring Boot – Introduction
  • Spring Boot – Starter parent
  • Spring Boot – Starter templates
  • Spring Boot – Multi-module project
  • Spring Boot – Annotations
  • Spring Boot – Auto configuration
  • Spring Boot – AOP
  • Spring Boot – Logging
  • Spring Boot – DevTools
  • Spring Boot – WAR Packaging
  • Spring Boot – REST API
  • Spring Boot – CRUD
  • Spring Boot – OAuth2
  • Spring Boot – Testing
  • Spring Boot – RestTemplate
  • Spring Boot – Thymeleaf
  • Spring Boot – Hibernate
  • Spring Boot – DataSource
  • Spring Boot – Error Handling
  • Spring Boot – Caching
  • Spring Boot – Retry
  • Spring Boot – BasicAuth
  • Spring Boot – H2 Database
  • Spring Boot – Ehcache 3.x
  • Spring Boot – Gson
  • Spring Boot – RMI
  • Spring Boot – Send Email
  • Spring Boot – Interview Questions

Spring Boot Tutorial

  • Spring Boot – CommandLineRunner
  • Spring Boot – Configure Jetty
  • Spring Boot – Tomcat Default Port
  • Spring Boot – Context Root
  • Spring Boot – SSL [https]
  • Spring Boot – Get all loaded beans
  • Spring Boot – PropertyEditor
  • Spring Boot – @EnableScheduling
  • Spring Boot – Jersey
  • Spring Boot – SOAP Webservice
  • Spring Boot – SOAP Client
  • Spring Boot – JMSTemplate
  • Spring Boot – REST APIs
  • Spring Boot – JSP View
  • Spring Boot – Actuator endpoints
  • Spring Boot – Role Based Security
  • Spring Boot – RSS / ATOM Feed
  • Spring Boot – Ehcache 2.x

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces