You will learn aspect programming by implementing a Spring AOP custom annotation to log the execution time of a method without modify its code. AOP stands for Aspect-Oriented Programming
Add Spring AOP into your project
Add spring-boot-starter-aop
into your project as a dependency on pom.xml or build.gradle file. The library versions can be omitted as it is resolved by the parent pom provided by Spring Boot
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
</dependencies>
You can find the full pom.xml file as below
Create a custom annotation
In Java, you can use @interface
to define an annotation type as the following
Target
indicates the contexts in which an annotation type is applicable. The contexts can be ElementType.METHOD
and ElementType.TYPE
Retention
indicates how long annotations with the annotated type are to be retained. The default value is RetentionPolicy.CLASS
which is only retained by the compiler. RetentionPolicy.RUNTIME
is retained by both the compiler at compile-time and VM at run-time
Create an aspect
Use AspectJ annotations such as @Aspect
and @Around
to declare aspect and advice
The logExecutionTime
is only applied to method annotated with @LogExecutionTime
thanks to this advice @Around("@annotation(LogExecutionTime)")
Apply to a method
Add @LogExecutionTime
to a method
Run and test
You can run the application by typing the following command on the terminal console at the project root directory
$ mvn clean spring-boot:run
You would see something like this text in the console
CommandLineRunner com.hellokoding.spring.Application.commandLineRunner(ApplicationContext)
executed in 11ms
Conclusion
In this tutorial, we learned to create a custom annotation and apply it to a method by using Spring AOP and AspectJ annotations. You can find the full source code at GitHub https://github.com/hellokoding/hellokoding-courses/tree/master/spring-examples/spring-aop-example