Sub topic 2
How Spring Decides Which Proxy to Create
Assume Core Java, interfaces, annotations, and basic Spring dependency injection. Spring AOP applies advice by wrapping a Spring-managed bean in a proxy. Calls made through that proxy can run extra behavior before or after the target method.
Choosing JDK or CGLIB
Spring chooses the proxy type from the target class:
- JDK dynamic proxy: Implements the target's interfaces. The injected reference should use an interface type.
- CGLIB proxy: Creates a subclass of the target class. Spring uses this when class-based proxying is enabled or when there is no suitable interface.
Spring Boot enables AOP when spring-boot-starter-aop is present. You can enable it explicitly with @EnableAspectJAutoProxy. Set proxyTargetClass = true to request CGLIB proxies.
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
class AopConfig {
}
@Aspect
@Component
@Order(1)
class TimingAspect {
@Around("execution(* com.example.service..*(..))")
Object time(ProceedingJoinPoint call) throws Throwable {
long start = System.nanoTime();
try {
return call.proceed();
} finally {
long elapsedMs = (System.nanoTime() - start) / 1_000_000;
System.out.println(call.getSignature().toShortString()
+ " took " + elapsedMs + " ms");
}
}
}Enabling an Aspect
An aspect is a class that combines a pointcut with advice. @Aspect marks the class, and @Component registers it as a Spring bean. @EnableAspectJAutoProxy tells Spring to create proxies for matching beans.
Selecting Join Points
A join point is an operation that can be intercepted. Spring AOP mainly supports method execution join points. A pointcut selects those operations.
Common expressions include:
execution(* com.example.service..*(..)): every method in a package and its subpackages.within(com.example.service..*): methods declared in matching classes.@annotation(Audited): methods carrying@Audited.
Use narrow pointcuts. A broad expression can add logging or security checks to framework methods you did not intend to intercept.
Advice Types
Advice is the code that runs at a selected join point.
@Before: runs before the method.@AfterReturning: runs after normal completion.@AfterThrowing: runs when the method throws.@After: runs whether the method succeeds or fails.@Around: controls the entire call.
Around Advice and Ordering
ProceedingJoinPoint.proceed() calls the target. If you omit it, the target does not run. Use try and finally when cleanup must happen after both success and failure.
Multiple aspects can match one method. Use @Order to control them. Lower values run first on entry and last on exit.
Exercise
What proxy type does Spring normally use for a bean that implements an interface?
Show answer
A JDK dynamic proxy. Enable class-based proxying with proxyTargetClass=true when you need a CGLIB proxy.