Correctness13 - SpotBugsExtensionForSpringFrameWork/CS5098 GitHub Wiki

Bug pattern name: Proxied Beans #BeansExceptions

Description

When a bean in the context is proxied using the JDK Dynamic Proxy mechanism, then the proxy will not extend the target bean (it will, however, implement the same interfaces).

Because of this, if the bean is injected by an interface, it will be correctly wired in. If however the bean is injected by the actual class, then Spring will not find a bean definition that matches the class – since the proxy does not actually extend the class.

A very common reason the bean may be proxied is the Spring transactional support – namely beans that are annotated with @Transactional.

For example, if ServiceA injects ServiceB, and both services are transactional, injecting by the class definition will not work:

@Transactional
public class ServiceA implements IServiceA{

    @Autowired
    private ServiceB serviceB;
    ...
}

@Service
@Transactional
public class ServiceB implements IServiceB{
    ...
}

Solution

@Service
@Transactional
public class ServiceA implements IServiceA{

    @Autowired
    private IServiceB serviceB; // Change to interface 
    ...
}

@Service
@Transactional
public class ServiceB implements IServiceB{
    ...
}

Reference List

baeldung