Spring 事务管理配置方法
Spring中声明式的事务配置方法有两种,一种是注解方式,另一种可能用AOP切片方式来实现。
一、注解方式
- 在Spring配置文件中加入配置
<!-- DataSource配置 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" p:driverClass="${jdbc.driverClassName}" p:jdbcUrl="${jdbc.url}" p:user="${jdbc.username}" p:password="${jdbc.password}" /> <!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 开启事务注解 --> <tx:annotation-driven transaction-manager="transactionManager"/>
- 具体应用
package test.spring.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import test.spring.Dao.ProductDao; import test.spring.model.Product; //用注解使用事务 //propagation事物传递参数,默认为propagation="REQUIRED",表示当有几个方法同时使用时,将视同一个事务处理,为REQUIRES_NEW时,视为多个事务处理 //Propagation.REQUIRES_NEW @Transactional(propagation = Propagation.REQUIRES_NEW ) @Service("prodcutService") public class ProdcutServiceImpl extends BaseService<Product> implements ProductService { @Autowired private ProductDao prodao; @Override //设置该方法为只读 @Transactional (readOnly = true ) public Product getPro(int pid) { // 具体业务省略。。。。。。。。。。。。。。。。。。。 return null; } }
二、AOP切片方式
- 在spring配置文件中加入
<!-- DataSource配置 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" p:driverClass="${jdbc.driverClassName}" p:jdbcUrl="${jdbc.url}" p:user="${jdbc.username}" p:password="${jdbc.password}" /> <!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置事务属性 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 以get开头的方法设定为只读 ,还有propagation事物传递参数,默认为propagation="REQUIRED",表示当有几个方法同时使用时,将视同一个事务处理,为REQUIRED_New时,视为多个事务处理 --> <tx:method name="get*" read-only="true" /> <tx:method name="find*" read-only="true" /> <tx:method name="select*" read-only="true" /> <!-- 除上面设定条件的方法外,全部为false,也是默认的设置 --> <tx:method name="*" read-only="false" /> </tx:attributes> </tx:advice> <!-- 配置事务的切入点 --> <aop:config> <!-- 切入点为test.spring.service包下面的所有类的所有方法 --> <aop:pointcut expression="excution(* test.spring.service.*.*(..))" id="txPointcut" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" /> </aop:config>
原文地址:https://blog.csdn.net/jingde528/article/details/140357528
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!