There are times when it is necessary to be able to log the execution time of a method. The simplest way to achieve that would be to modify every method adding
System.currentTimeMillis() at the beginning and at the end of the method. But it leads us to the following inconvenience:
- the same code should be repeated many times
- there is no easy way to turn on and off that
But there is a more elegant way to achieve that, keeping measuring code in one single place without method's body modification. And the answer is AOP.
Aspect-oriented Programming (AOP) complements Object-oriented Programming (OOP) by providing another way of thinking about program structure. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Aspects enable the modularization of concerns (such as transaction management) that cut across multiple types and objects. (Such concerns are often termed “crosscutting” concerns in AOP literature.)
I'm going to use Spring AOP to measure the execution time of a method.
First of all
spring-boot-starter-aop dependency needs to be added. Below is the example of the Maven configuration.
The next step is to create a custom annotation that will be used to annotate a method that needs to be measured.
There is a message in the annotation to pass a custom message to the log.
The next step is to create an aspect that will use the
Measured annotation above.
What this code does:
@Aspectannotation declares that this class is an aspect
@Aroundannotation declares that the advice will be run before and after the target method
@annotation(net.fisenko.annotations.Measured)is a pointcut, which means that all methods annotated with
@Measuredwill be associated with this advice
- The advice itself is simply measures time before and after target method execution
Having the annotation and the aspect class the measurement becomes as simple as possible. For example: