Sub topic 19
Introductions: adding interfaces with @DeclareParents
This chapter assumes you know how Spring creates JDK and CGLIB proxies and how @Aspect classes with @Before advice work. It also assumes you have read the self-invocation chapter. Introductions are the one Spring AOP feature that changes what a bean is, not only what happens when its methods run.
What an introduction does
Normal advice runs around existing methods. An introduction adds a new interface to a bean, together with an implementation of that interface. The proxy Spring builds implements the bean's original interfaces and also the introduced one. Calls to the introduced methods never reach the target. A separate delegate object handles them.
This works like a mixin. You can give many unrelated beans a capability, such as usage counting, a "last modified" timestamp or a lock flag, without touching their source or making them extend a base class.
Declaring an introduction
You declare an introduction with @DeclareParents on a field inside an @Aspect class. The field's type is the interface to add. The annotation has two attributes:
valueis a type pattern that selects which bean classes receive the interface. A trailing+means "this type and its subtypes".defaultImplis the class that implements the introduced interface.
The field is only a carrier for the annotation. Spring never reads or assigns it.
First, the interface and its implementation:
package com.example.tracking;
public interface UsageTracked {
void recordUse();
int getUseCount();
}package com.example.tracking;
import java.util.concurrent.atomic.AtomicInteger;
public class DefaultUsageTracked implements UsageTracked {
private final AtomicInteger count = new AtomicInteger();
@Override
public void recordUse() {
count.incrementAndGet();
}
@Override
public int getUseCount() {
return count.get();
}
}Next, the aspect. It adds the interface and also uses it. The this(tracked) designator binds the proxy (not the target) to the advice parameter, and only matches beans whose proxy implements UsageTracked.
package com.example.tracking;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.DeclareParents;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class UsageTrackingAspect {
@DeclareParents(value = "com.example.service.*Impl",
defaultImpl = DefaultUsageTracked.class)
public static UsageTracked mixin;
@Before("execution(* com.example.service.*.*(..)) && this(tracked)")
public void record(UsageTracked tracked) {
tracked.recordUse();
}
}Finally, a bean to enhance and a demo that runs it:
package com.example.service;
public interface OrderService {
void place(String item);
}package com.example.service;
import org.springframework.stereotype.Service;
@Service
public class OrderServiceImpl implements OrderService {
@Override
public void place(String item) {
System.out.println("placing " + item);
}
}package com.example;
import com.example.service.OrderService;
import com.example.tracking.UsageTracked;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@ComponentScan("com.example")
@EnableAspectJAutoProxy
public class IntroductionDemo {
public static void main(String[] args) {
try (var ctx = new AnnotationConfigApplicationContext(IntroductionDemo.class)) {
OrderService service = ctx.getBean(OrderService.class);
service.place("book");
service.place("pen");
UsageTracked tracked = (UsageTracked) service;
System.out.println("uses: " + tracked.getUseCount());
}
}
}The output is:
placing book
placing pen
uses: 2The cast from OrderService to UsageTracked succeeds only because the bean is a proxy. OrderServiceImpl does not implement UsageTracked. The proxy does.
How it works internally
For each @DeclareParents field, Spring registers an introduction advisor. During proxy creation, the advisor tells the ProxyFactory to add the introduced interface to the proxy's interface list. It also installs an interceptor, based on DelegatingIntroductionInterceptor. That interceptor checks whether the invoked method belongs to the introduced interface. If so, it calls the delegate. If not, it lets the call continue down the chain to the target.
The consequences follow from this:
- One delegate per proxy. Each bean instance gets its own
DefaultUsageTracked. A singleton bean has one counter. A prototype bean gets a fresh counter each time. The delegate is shared across threads, so make it thread-safe, asAtomicIntegerdoes here. - Both proxy types work. A JDK proxy lists the introduced interface alongside the bean's own interfaces. A CGLIB proxy implements it as well.
- Injection by concrete class can fail. With a JDK proxy, the bean is not an
OrderServiceImpl. Inject by interface, or setproxyTargetClass = true.
Gotchas
| Situation | What happens |
|---|---|
| The introduced interface sits in a package your `execution(...)` pointcut matches | Calls such as `recordUse()` pass through your advice too, which can cause recursion. Keep the mixin interface outside advised packages, as above. |
| You call `this.getUseCount()` inside the target | Compile error or `ClassCastException`. The target does not implement the interface, only the proxy does. |
| Code holds a reference to the raw target | No introduced interface exists there. This is the self-invocation rule again. |
| The pattern in `value` matches a `final` class | CGLIB cannot subclass it, so proxy creation fails unless the class has a JDK-proxyable interface. |
| The bean is not managed by Spring | No proxy exists, so no introduction. |
You can confirm the proxy at runtime with AopUtils.isAopProxy(service) and by printing service.getClass().getInterfaces(). The array includes UsageTracked.
Introductions and AspectJ
Spring AOP supports @DeclareParents only for Spring beans, and only through proxies. Full AspectJ weaving can do the same thing at the bytecode level with inter-type declarations. The woven class itself implements the interface, so there is no proxy and no cast restriction, and it works on objects created with new. The cost is a compiler or load-time agent in your build.
Exercise
In the demo, service.place("book") increments the counter through @Before advice. Why does tracked.recordUse() called inside that advice not trigger the same advice again?
Show answer
The pointcut is execution(* com.example.service.*.*(..)), and recordUse() is declared on UsageTracked in com.example.tracking, which is outside that package. The call goes through the proxy to the mixin delegate and matches no advice. If the interface were in com.example.service, the pointcut would match it and the advice would recurse.
Exercise
A bean is a CGLIB proxy of OrderServiceImpl, and a @DeclareParents aspect adds UsageTracked. A colleague asks whether ((UsageTracked) this) is valid inside OrderServiceImpl.place. What do you answer?
Show answer
No. Inside the class, this is the raw target, which does not implement UsageTracked, so the cast throws ClassCastException. Only the proxy implements the introduced interface. To reach it, inject the bean into another bean, or obtain the current proxy with AopContext.currentProxy() after setting exposeProxy = true.