Search code examples
springspring-bootspring-aopspring-transactionsspring-aspects

Could not @Autowire implementation class, proxy mix-up


I am using Spring-boot to create a multi-module Maven application. I have the service layer in one module, the web layer in another. I can't start the application, having the following error:

The bean 'Service' could not be injected as a 'Service' because it is a JDK dynamic proxy that implements:


Action:

Consider injecting the bean as one of its interfaces or forcing the use of CGLib-based proxies by setting proxyTargetClass=true on @EnableAsync and/or @EnableCaching.

Tried annotating configuration classes with

@EnableAsync(proxy-target-class=true)
@EnableCaching(proxy-target-class=true)
@EnableTransactionManagement(proxy-target-class=true)
@EnableAspectJAutoProxy(proxy-target-class=true)

As soon as I add any annotation of the type @PreAuthorize or @Transactional the application stops working.

The service doesn't implement any interface, I want Spring to use CGLib proxy for auto-wiring and from the trace log, I see the following:

* Adding transactional method 'Service.remove' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
* Creating implicit proxy for bean 'Service' with 0 common interceptors and 3 specific interceptors.
* Creating CGLIB proxy: SingletonTargetSource for target object [Service@17765082]
* Adding transactional method 'Service$$EnhancerBySpringCGLIB$$6f15732.remove' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
* Creating implicit proxy for bean 'Service' with 0 common interceptors and 2 specific interceptors
* Creating JDK dynamic proxy: SingletonTargetSource for target object [Service$$EnhancerBySpringCGLIB$$6f15732@32142479]

The exception for auto-wiring is:

Bean named 'locationService' is expected to be of type 'Service' but was actually of type 'com.sun.proxy.$Proxy202'

Does this mean that Spring is registering my service both as CGLib proxy and JDK proxy? If thats the case, how can I force it to use only the CGLib proxy?


Solution

  • Problem solved on a hunch. Spring AOP works correctly, and uses CGLib proxy as expected. Problem was a dependency which did an override of the proxy.

    I was using JavaMelody for monitoring and it was creating JDK proxies for the CGLib created proxies.

    None the less, removing Java Melody, or configuring it to work with CGLib, as stated here JavaMelody-ISSUE-502 solves the problem and the application works as expected.