With Spring’s proxy-based configuration, calling an @Async, @Cacheable, or @Transactional method from its
own class bypasses the proxy that applies the annotation’s behavior. For example, an @Async method runs on the calling thread instead of
being scheduled asynchronously. Move the annotated operation to a separate Spring-managed bean and call it through an injected reference.
The example assumes asynchronous method execution is enabled with @EnableAsync and both services are discovered by component scanning.
Constructor injection gives the calling service a reference to the managed bean, allowing Spring’s proxy to intercept the call.
@Service
public class NotificationProcessor {
public void process(String message) {
sendAsync(message); // Noncompliant: call bypasses the proxy
}
@Async
public void sendAsync(String message) {
System.out.println(message);
}
}
Put these services in separate source files.
@Service
public class NotificationProcessor {
private final NotificationSender sender;
public NotificationProcessor(NotificationSender sender) {
this.sender = sender;
}
public void process(String message) {
sender.sendAsync(message);
}
}
@Service
public class NotificationSender {
@Async
public void sendAsync(String message) {
System.out.println(message);
}
}
The annotations are org.springframework.stereotype.Service, org.springframework.scheduling.annotation.Async, and
org.springframework.scheduling.annotation.EnableAsync.
The same call boundary matters for caching and transactions:
@Cacheable: self-invocation bypasses the cache lookup and population that would wrap the call.@Transactional: self-invocation does not apply the called method’s transaction settings. The method may still run in a transaction
already started by its caller.Enable the relevant Spring feature and use a method that the configured proxy can intercept. Creating the collaborator with new
bypasses Spring management and does not fix the problem. This explanation concerns proxy mode; AspectJ weaving has different self-invocation
behavior.
Avoid using self-injection as the default solution. It introduces a circular dependency and depends on configuration that may reject circular references. Separating the operation into a collaborating bean makes the intercepted call explicit.