今天想做事务控制,在启动器类上加了**@EnableTransactionManagemen**t来开启事务,并在service层方法上加上了 @Transactional(rollbackFor = Exception.class),如何启动启动器类,就报如下错误了,第一次碰到
版本:
org.springframework.boot spring-boot-starter-parent 2.2.7.RELEASE
2023-03-16 15:13:56.330 WARN 1244 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'excelDemo': Unsatisfied dependency expressed through field 'resoucefileService'; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'resoucefileServiceImpl' is expected to be of type 'com.example.demo.service.impl.ResoucefileServiceImpl' but was actually of type 'com.sun.proxy.$Proxy96'
2023-03-16 15:13:56.333 INFO 1244 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2023-03-16 15:13:56.343 INFO 1244 --- [ main] ConditionEvaluationReportLoggingListener : Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2023-03-16 15:13:56.346 ERROR 1244 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter : ***************************
APPLICATION FAILED TO START
***************************Description:The bean 'resoucefileServiceImpl' could not be injected as a 'com.example.demo.service.impl.ResoucefileServiceImpl' because it is a JDK dynamic proxy that implements:com.example.demo.service.IResoucefileServiceAction: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.Process finished with exit code 1
翻译一下:
上下文初始化期间遇到异常 -
取消刷新尝试:org.springframework.beans.factory.UnsatisfiedDependency异常:创建名为“excelDemo”的Bean时出错:通过字段“resoucefileService”表示的不满意依赖项;嵌套异常是org.springframework.beans.factory.BeanNotOfRequiredTypeException:名为“resoucefileServiceImpl”的Bean应该属于“com.example.demo.service.impl.ResoucefileServiceImpl”类型,但实际上“com.sun.proxy.$Proxy 96”类型。
描述:
bean ‘resoucefileServiceImpl’ 无法作为’com.example.demo.service.impl.ResoucefileServiceImpl’ 注入,因为它是一个 JDK动态代理,它实现了: com.example.demo.service.IResoucefileService行动:
考虑将 Bean 注入为其接口之一,或者通过在@EnableAsync和/或@EnableCaching上设置
proxyTargetClass=true 来强制使用基于 CGLib 的代理。
解决方法(强制使用CGLIB的代理)
(一)
(二)
我用的是mybatisPlus框架,mybatis底层是基于jdk的代理方式
查看报错,可知我的service层是基于jdk动态代理生成的。
而springboot2.o则默认是基于cglib的代理方式,而我在方法上用**@Transactional(rollbackFor = Exception.class)**注解,该注解的目标主要是用于控制数据库事务,那么它的内部必须通过AOP切面的方法去实现事务控制,所以会用到动态代理,而且是采用CGLib。
这样就会产生冲突,所以需要强制Springboot使用cglib的代理方式来生成。