Sub topic 3
Building an Annotation-Driven Aspect
Assume you know Java interfaces, annotations, basic Spring dependency injection, and how Spring beans are created.
Apply advice with a custom annotation
A custom annotation marks exactly which methods should receive extra behavior. The aspect matches the annotation and can read its attributes.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Audited {
String action();
}
@Aspect
@Component
public class AuditAspect {
@Around("@annotation(audited)")
public Object audit(ProceedingJoinPoint point, Audited audited)
throws Throwable {
System.out.println("start: " + audited.action());
Object result = point.proceed();
System.out.println("end: " + audited.action());
return result;
}
}The annotated method must be called through its Spring proxy for this advice to run.
Why self-invocation skips advice
A call from one bean method to another method in the same object uses this, not the proxy.
public void saveAll(List<String> names) {
for (String name : names) {
saveReport(name); // bypasses the proxy
}
}Move saveReport to another bean, or call it through an injected bean reference. Avoid using the current object’s proxy as a workaround unless the design requires it.
Proxy limitations
Spring AOP proxies cannot advise:
- Private methods, because callers cannot dispatch through them.
- Final methods on class-based proxies, because they cannot be overridden.
- Objects created with
new, because Spring does not manage them. - Calls that never cross the proxy boundary, including self-invocation.
`@Transactional` uses the same mechanism
@Transactional is proxy-based advice. A transaction starts when an external caller enters the proxied method. A private transactional method, a final method, or a self-invocation does not reliably create the declared transaction boundary.
Inspect and create proxies
Use AopUtils.isAopProxy(bean) while debugging. If it returns false, check that the object is a Spring bean, AOP is enabled, and the pointcut matches.
For a manually created proxy:
ProxyFactory factory = new ProxyFactory(new GreetingServiceImpl());
factory.addAdvice((MethodInterceptor) invocation -> {
System.out.println("before");
return invocation.proceed();
});
GreetingService proxy = (GreetingService) factory.getProxy();Introductions and AspectJ
An introduction adds an interface implementation to an existing bean, commonly with @DeclareParents. It is useful when clients need a capability that the target class does not declare.
Choose AspectJ compile-time or load-time weaving when you need to intercept self-invocation, constructors, private methods, or objects outside Spring. Weaving has broader reach but adds build or runtime configuration.
Exercise
Why does a direct call from one method to another method on the same bean skip @Transactional advice?
Show answer
The call uses this and bypasses the Spring proxy, so proxy advice never receives the call.