Skip to main content
AOP and proxies · Topic 2 of 5

Around advice

Definition​

An @Around advice runs code before and after a method call and decides whether the method runs at all. It is how you add timing, logging or retries to many methods without editing them.

Example code​

Timing every call of a service

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Service
class PriceService {
int priceOf(String item) { return item.length() * 10; }
}

@Aspect
@Component
class LoggingAspect {
@Around("execution(* PriceService.*(..))") // every method of PriceService
Object log(ProceedingJoinPoint call) throws Throwable {
System.out.println("before " + call.getSignature().getName());
Object result = call.proceed(); // run the real method
System.out.println("after, result = " + result);
return result;
}
}

@ComponentScan
@EnableAspectJAutoProxy
class Demo {
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Demo.class)) {
context.getBean(PriceService.class).priceOf("book");
}
}
}

// Output:
// before priceOf
// after, result = 40

Finished this page? Track your progress (saved only in your browser).