<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
package dev.gayerie.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class SupervisionAspect {
@Around("@annotation(supervision)")
public Object superviser(ProceedingJoinPoint joinPoint, Supervision supervision)
throws Throwable {
long maxDuree = supervision.dureeMillis();
long start = System.currentTimeMillis();
try {
return joinPoint.proceed(joinPoint.getArgs());
} finally {
long end = System.currentTimeMillis();
long duree = end - start;
if (duree > maxDuree) {
System.out.printf("Attention l'appel à %s à durée %dms soit %dms de plus qu'attendu%n",
joinPoint.toShortString(), duree, duree - maxDuree);
}
}
}
}
package dev.gayerie;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LogAspect {
@Before("execution(public * dev.gayerie.*Service.*(..))")
public void log(JoinPoint joinPoint) {
System.out.printf("Appel de %s avec %d paramètres%n",
joinPoint.toShortString(),
joinPoint.getArgs().length);
}
}
package dev.gayerie;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@EnableAspectJAutoProxy
@Configuration
@ComponentScan
public class Application {
public static void main(String[] args) throws InterruptedException {
try (AnnotationConfigApplicationContext appCtx =
new AnnotationConfigApplicationContext(Application.class)) {
// ...
}
}
}
package dev.gayerie;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Supervision {
int dureeMillis();
}
package dev.gayerie;
import org.springframework.stereotype.Service;
@Service
public class BusinessService {
@Supervision(dureeMillis = 5)
public void doSomething() {
System.out.println("réalise un traitement important pour l'application");
// ...
}
}