【问题标题】:Could not @Autowire implementation class, proxy mix-up无法@Autowire 实现类,代理混淆
【发布时间】:2020-03-06 02:28:01
【问题描述】:

我正在使用 Spring-boot 创建一个多模块 Maven 应用程序。我在一个模块中有服务层,在另一个模块中有 Web 层。我无法启动应用程序,出现以下错误:

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.

尝试用

注释配置类
@EnableAsync(proxy-target-class=true)
@EnableCaching(proxy-target-class=true)
@EnableTransactionManagement(proxy-target-class=true)
@EnableAspectJAutoProxy(proxy-target-class=true)

只要我添加了@PreAuthorize 或@Transactional 类型的任何注释,应用程序就会停止工作。

该服务没有实现任何接口,我希望 Spring 使用 CGLib 代理进行自动装配,从跟踪日志中,我看到以下内容:

* 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]

自动连线的例外是:

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

这是否意味着 Spring 将我的服务同时注册为 CGLib 代理和 JDK 代理? 如果是这样,我怎么能强制它只使用 CGLib 代理?

【问题讨论】:

    标签: spring spring-boot spring-aop spring-transactions spring-aspects


    【解决方案1】:

    凭直觉问题解决了。 Spring AOP 工作正常,并按预期使用 CGLib 代理。问题是一个覆盖代理的依赖项。

    我使用 JavaMelody 进行监控,它正在为 CGLib 创建的代理创建 JDK 代理。

    不过,删除 Java Melody,或将其配置为与 CGLib 一起使用,如JavaMelody-ISSUE-502 所述,可以解决问题,并且应用程序按预期工作。

    【讨论】:

    • 请接受您自己的答案以结束问题。谢谢你。 :-)
    猜你喜欢
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-26
    • 1970-01-01
    • 2015-11-29
    相关资源
    最近更新 更多