1、問題背景
今天做項目,發現配置好@Transactional后,沒有生效,事務沒有回滾,即便在網上查資料,也沒有解決,好像網上沒有人發過我遇見的這種情況的帖子。
2、自己遇到的情況分析
代碼結構圖

控制層代碼
@RequestMapping("/update")
@ResponseBody
public Object updateStu(int age) {
try {
transactionService.updateStudent(age);
return "success";
} catch (Exception e) {
return e.getMessage();
}
}
TransactionServiceImpl內代碼
@Service
public class TransactionServiceImpl implements TransactionService {
@Resource
StudentServiceImpl studentService;
@Transactional(rollbackFor = Exception.class)
public void updateStudent(int age) {
Student stu1 = studentService.getStudentById(1);
Student stu2 = studentService.getStudentById(2);
stu1.setAge(age);
stu2.setAge(age);
studentService.updateStudent(stu1);
int a = 1 / 0;
studentService.updateStudent(stu2);
}
}
applicationContext.xml中配置事務
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <tx:annotation-driven transaction-manager="transactionManager"/>
最開始spring-mvc.xml配置的掃描包是:<context:component-scan base-package="com.zhi">,當運行程序后,訪問controller,第一個更新操作事務沒有回滾。
最后查找問題原因,是spring-mvc的包掃描問題。
啟動程序,現根據spring監聽創建spring上下文,在spring掃描包的時候,會將TransactionServiceImpl對象放進spring上下文中。然后程序會繼續加載springmvc的配置,創建springmvc上下文,這是掃描包時,會將TransactionServiceImpl對象放入springmvc上下文中。當訪問接口時,是由springmvc上下文中的controller從springmvc上下文中獲取到TransactionServiceImpl對象。當執行到@Transactional注解的方法時,spring aop會判斷是否創建代理對象。問題就在這里,因為事務在spring上下文中配置,但是獲取到的對象時在springmvc上下文中,所以spring無法創建代理對象,因此@Transactional注解最終不會生效。
3、其他@Transactional不生效原因
參考:https://blog.csdn.net/qq_20597727/article/details/84900994
