How to run an aspect in Spring using annotations, without xml file?
Many other tutorials using xml file for configuration ascpect.
Advantages of Spring Boot:It avoids writing lots of boilerplate Code, Annotations and XML Configuration. It is very easy to integrate Spring Boot Application with its Spring Ecosystem like Spring JDBC, Spring ORM, Spring Data, Spring Security etc.
To enable @AspectJ, spring AOP provides @EnableAspectJAutoProxy annotation which will be annotated in java configuration. To work with spring AOP and @AspectJ support, we need to create a class annotated with @Aspect annotation.
JoinPoint: Joinpoint are points in your program execution where flow of execution got changed like Exception catching, Calling other method. PointCut: PointCut are basically those Joinpoints where you can put your advice(or call aspect). So basically PointCuts are the subset of JoinPoints.
The concept of join points as matched by pointcut expressions is central to AOP, and Spring uses the AspectJ pointcut expression language by default.
Define a custom annotation;
@Target({ElementType.TYPE ,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface Loggable {
}
Annotate your method that you want to intercept ;
@Service
public class MyAwesomeService {
@Loggable
public void myAwesomemethod(String someParam) throws Exception {
// do some awesome things.
}
}
Add aspect dependencies to your pom.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
and define your aspects class ;
@Aspect
@Component
public class LoggingHandler {
@Before("@annotation(com.example.annotation.Loggable)")
public void beforeLogging(JoinPoint joinPoint){
System.out.println("Before running loggingAdvice on method=");
}
@After("@annotation(com.example.annotation.Loggable)")
public void afterLogging(JoinPoint joinPoint){
System.out.println("After running loggingAdvice on method=");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With