7

How to run an aspect in Java.

How to run an aspect in Spring using annotations, without xml file?

Many other tutorials using xml file for configuration ascpect.

Community
  • 1
  • 1
Stack Over
  • 143
  • 2
  • 12

2 Answers2

8

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=");
    }
}
Tunceren
  • 754
  • 1
  • 8
  • 16
0

Use annotations on your class: @Component @Aspect

aussie
  • 119
  • 5