Declarative Transaction Demarcation
我们推荐你使用 Spring 的声明式事务支持,它可以让你用 AOP 事务拦截器取代 Java 代码中明确的事务分界 API 调用。你可以通过使用 Java 注解或 XML 在 Spring 容器中配置这个事务拦截器。这种声明式事务能力让你保持业务服务不受重复的事务分界代码的影响,而专注于增加业务逻辑,这才是你的应用程序的真正价值所在。
:::info 在你继续之前,我们强烈建议你阅读 声明式事务管理,如果你还没有这样做的话。 :::
你可以用 @Transactional 注解来注解服务层,并指示 Spring 容器找到这些注解,并为这些被注解的方法提供事务性语义。下面的例子展示了如何做到这一点。
public class ProductServiceImpl implements ProductService {private ProductDao productDao;public void setProductDao(ProductDao productDao) {this.productDao = productDao;}@Transactionalpublic void increasePriceOfAllProductsInCategory(final String category) {List productsToChange = this.productDao.loadProductsByCategory(category);// ...}@Transactional(readOnly = true)public List<Product> findAllProducts() {return this.productDao.findAllProducts();}}
在容器中,你需要设置 PlatformTransactionManager 实现(作为一个 bean)和一个 <tx:annotation-driven/>条目,在运行时选择进入@Transactional处理。下面的例子展示了如何做到这一点:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beanshttps://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/txhttps://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/aophttps://www.springframework.org/schema/aop/spring-aop.xsd"><!-- SessionFactory, DataSource, etc. omitted --><bean id="transactionManager"class="org.springframework.orm.hibernate5.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory"/></bean><tx:annotation-driven/><bean id="myProductService" class="product.SimpleProductService"><property name="productDao" ref="myProductDao"/></bean></beans>
