SoFunction
Updated on 2025-04-15

SpringBoot elegantly implements calculation method execution time

Calculate method execution time is a common non-functional requirement in most backend applications. Here are some traditional methods for calculating execution time:

long startTime = (());
// Your logic codelong executionTime = (() - startTime) / 1000;
("The time spent on calculation is:{} Second", executionTime);

StopWatch watch = new StopWatch();
();
// Your logic code();
("The time spent on calculation is:{} Second", ());

It can be seen that the same calculation code needs to be added to each method that needs to calculate the execution time. This way of stating the execution time of the code has problems such as code redundancy, violation of DRY principles, and strong invasiveness.

Next, let's use AOP to implement the function of adding an annotation at the top of the method, which can calculate the execution time of all methods very efficiently.

Step 1: Enable Spring AOP

First, enable Spring AOP by adding the following in :

<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

Step 2: Create a custom annotation

Now let's create a custom annotation called ExecutionTimeLogger in Spring Boot. As you can see, the annotation works at runtime and is applicable to the method level.

@Target()
@Retention()
public @interface ExecutionTimeLogger {
}

Step 3: Create a facet class

Create a new class as a slit, containing the logic to calculate the execution time of the method. There are many ways to use sections in Spring AOP, and the @Around annotation is used here. Create the ExecutionTimeLoggerAspect class and use the @Aspect annotation, then create the executionTimeLogger method and add the @Around annotation, and pass the annotation name as a parameter to @Around, so that the method will be called before and after the method with the ExecutionTimeLogger annotation is executed:

@Aspect
@Component
publicclass ExecutionTimeLoggerAspect {
    static final Logger logger = ();

    @Around("@annotation(ExecutionTimeLogger)")
    public Object executionTimeLogger(ProceedingJoinPoint joinPoint) {
        try {
            long startTime = ();
            Object proceed = ();
            long executionTime = (() - startTime);
            ("{}Method in{}Completed within milliseconds", (), executionTime);
            return proceed;
        } catch (Throwable e) {
            ("In calculation{}An error occurred while executing the method", (), e);
            return null;
        }
    }
}

Step 4: Use custom annotations

All required configurations are completed. Now the only thing we need to do is use this annotation where we want to calculate the execution time of the method in Java code. Assume that the execution time of the method is to be calculated, as shown in the following code. Just add annotations at the top of the method.

public class CustomLoggingService {
    @ExecutionTimeLogger
    public void myMethod() {
        try {
            (20000);
        } catch (InterruptedException e) {
            ();
        }
    }
}

Step 5: View the output

Output when myMethod is executed in your code:

|void () method is executed within 20 milliseconds

Isn't it very simple? Imagine how much time and effort you saved. Just write the code that calculates the execution time and continue to use the annotation where you need to calculate the execution time.

Let's summarize

1. Create custom annotations.

2. Create the @Aspect class, including methods to calculate execution time.

3. Declare the method with @Around and specify it as a custom annotation to execute.

4. Add annotations to the method to record the execution time.

This is the article about the execution time of SpringBoot's elegant implementation of calculation method. For more related contents of SpringBoot's calculation method, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!