1.原因
EasyExcel使用了监听器,没有被Spring进行管理,所以无法使用Spring的事务注解进行事务的相关操作
2.解决办法
代码语言:java复制通过构造器注入事务处理
//事务管理器
private PlatformTransactionManager platformTransactionManager;
//事务定义
private TransactionDefinition transactionDefinition;
//
private TransactionStatus transactionStatus = null;
public XXXListener(PlatformTransactionManager platformTransactionManager, TransactionDefinition transactionDefinition){
this.platformTransactionManager = platformTransactionManager;
this.transactionDefinition = transactionDefinition;
//开启事务
this.transactionStatus = platformTransactionManager.getTransaction(this.transactionDefinition);
}
@Override
public void invoke(TopicExcel topicExcel, AnalysisContext analysisContext) {
// 判断事务是否关闭,如果事务已经关闭不执行业务代码
if (transactionStatus.isCompleted()) {
return;
}
//TODO 业务代码
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
//判断事务是否已被处理,未处理则进行提交事务
if (!transactionStatus.isCompleted()) {
//提交事务
platformTransactionManager.commit(transactionStatus);
}
}
@Override
public void onException(Exception exception, AnalysisContext context) throws Exception {
//回滚事务
platformTransactionManager.rollback(transactionStatus);
throw new Exception(exception.getMessage());
}