Cross-cutting concerns are aspects like logging, security, or transaction management that affect many parts of an application. Spring Boot uses AOP to separate these from core business logic.
@Aspect @Component public class LoggingAspect { @Around("@annotation(com.example.LogExecutionTime)") public Object logTime(ProceedingJoinPoint joinPoint) throws Throwable { long start = System.currentTimeMillis(); Object proceed = joinPoint.proceed(); long executionTime = System.currentTimeMillis() - start; System.out.println(joinPoint.getSignature() + " executed in " + executionTime + "ms"); return proceed; } }
The @Around advice runs code before and after the method. It calls proceed() to run the method and then logs the time.
The '..' in the expression means any subpackage depth. Option A matches all methods in com.example.service and its subpackages.
For Spring AOP to work, the aspect must be a Spring bean, typically annotated with @Component and scanned by Spring. Otherwise, it won't be applied.
public class Service { @LogExecutionTime public void process() throws InterruptedException { Thread.sleep(100); } } public class Main { public static void main(String[] args) throws InterruptedException { Service service = new Service(); service.process(); service.process(); } } @Aspect @Component public class LoggingAspect { @Around("@annotation(com.example.LogExecutionTime)") public Object logTime(ProceedingJoinPoint joinPoint) throws Throwable { long start = System.currentTimeMillis(); Object proceed = joinPoint.proceed(); long time = System.currentTimeMillis() - start; System.out.println(joinPoint.getSignature() + " executed in " + time + "ms"); return proceed; } }
The service instance is created manually with new, so Spring does not manage it and the aspect is not applied. No logging output appears.
