8.6.3 使用@Transactional
Spring还允许将事务配置放在Java类中定义,这需要借助于@Transactional注解,该注解即可用于修饰Spring Bean类,也可用于修饰Bean类中的某个方法。
如果使用@Transaction修饰Bean类,则表明这些事务设置对整个Bean类起作用;若果使用@Transactional修饰Bean类的某个方法,则表明这些事务设置只对该方法有效。
使用@Transactional时可指定如下属性:
⊙ isolation : 用于指定事务的隔离级别。默认为底层事务的隔离级别。
⊙ noRollbackFor : 指定遇到特定异常时强制不会滚事务。
⊙ noRollbackForClassName : 指定遇到特定的多个异常时强制不会滚事务。该属性值可以指定多个异常类名。
⊙ propagation : 指定事务传播行为。
⊙ readOnly : 指定事务是否只读。
⊙ rollbackFor : 指定遇到特定异常时强制回滚事务。
⊙ rollbackForClassName : 指定遇到特定的多个异常时强制回滚事务。该属性值可以指定多个异常类名。
⊙ timeout : 指定事务的超时时长。
package edu.pri.lime._8_6_3.dao; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; public class NewsDaoImpl implements NewsDao { @Override @Transactional(propagation=Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=5) public void insert(String title, String content) { } }
还需要让Spring根据注解来配置事务代理,所以还需要在Spring配置文件中增加如下:
xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="edu.pri.lime._8_6_2.dao"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost/spring"/>
<property name="user" value="root"/>
<property name="password" value="System"/>
<property name="maxPoolSize" value="40"/>
<property name="minPoolSize" value="2"/>
<property name="initialPoolSize" value="2"/>
<property name="maxIdleTime" value="30"/>
bean>
<bean id="transactionManager" class="org.spring.framework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
beans>
啦啦啦
啦啦啦