为了事务的一致性,我在实现数据持久化的方法上加了@Transactional(rollbackFor = Exception.class)
在启动类上加了@EnableTransactionManagement注解,启动发现项目报错
百度查询了下说是把@EnableTransactionManagement注解改为@EnableTransactionManagement(proxy-target-class=true)
启动项目运行正常了。
先看下我代码结构
controller层
@RestController
public class SCUploadFilesController {
@Autowired
SCUploadFilesServiceImpl uploadFilesService;
service层
@Service
@Transactional(rollbackFor = Exception.class)
public class SCUploadFilesServiceImpl implements ISCUploadFilesService {
}
public interface ISCUploadFilesService {
}
proxy-target-class=true表示基于类代理 ; =false表示基于接口代理
当我们在SCUploadFilesServiceImpl ,接口的实现类使用@Transactional注解时,spring创建了一个proxy class实现了ISCUploadFilesService 接口,基于接口注入的;
分析我们的代码发现:启动类我们使用的@EnableTransactionManagement 默认是false,使用接口代理的;而我们controller层使用的
@Autowired注解基于类型注入的,注入的是SCUploadFilesServiceImpl ,接口的实现类,因为我们是基于接口ISCUploadFilesService 代理,而autowired注入的是接口的实现类SCUploadFilesServiceImpl ,就会报错because it is a JDK dynamic proxy that implements
解决办法两种;
方法一
@EnableTransactionManagement改为@EnableTransactionManagement(proxy-target-class=true),基于类代理
方法二
controller层@Autowired注解的内容修改为接口的类名,基于接口代理
@Autowired
ISCUploadFilesService uploadFilesService;
: