Spring Transaction中是否需要exception处理?

我对使用Transaction进行exception处理有疑问。 为了清楚说明我的问题,我想展示我的配置:

                         

活动事务类是:

 @Transactional public class CustomerService extends BaseService implements ICustomerService { @Transactional(readOnly = true) public Customer getCustomerById(String id) { return getDaoProvider().getCustomerDao().getCustomerById(id); } @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = { Throwable.class }) public void addNewCustomer(CustomerDTO customerDTO) { Customer customer = new Customer(); customer.setCustomerId(customerDTO.getCustomerId()); customer.setCustomerName(customerDTO.getCustomerName()); customer.setActive(customerDTO.isActive()); getDaoProvider().getCustomerDao().save(customer); } } 

我的疑惑在于addNewCustomer方法。 我已经设置了rollbackFor = { Throwable.class }

它是如何工作的?

我还需要显式处理exception,如:

 @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = { Throwable.class }) public boolean addNewCustomer(CustomerDTO customerDTO) { Customer customer = new Customer(); customer.setCustomerId(customerDTO.getCustomerId()); customer.setCustomerName(customerDTO.getCustomerName()); customer.setActive(customerDTO.isActive()); try { getDaoProvider().getCustomerDao().save(customer); } catch (Throwable throwable) { return false; } return true; } 

强制我通过删除customer表中的列来创建exception,但是该exception不是try-catch块中的catch,而是我可以从我调用了addNewCustomer方法的托管bean中捕获该exception。

这是Spring文档的摘录

在其默认配置中,Spring Framework的事务基础结构代码仅在运行时未经检查的exception情况下标记用于回滚的事务; 也就是说,抛出的exception是RuntimeException的实例或子类。 (错误也将 – 默认情况下 – 导致回滚)。 从事务方法抛出的已检查exception不会导致在默认配置中回滚。

你设置rollbackFor = Throwable.class,现在Spring将回滚任何Exception / Error。 默认情况下,无论我们是否喜欢,Spring将仅针对RuintimeException进行回滚,否则进行提交

Spring框架只抛出RuntimeExceptions,从技术上讲,你永远不必捕获任何exception。