Spring事务配置总结:
方法1:
ApplicationContent.xml配置:
Beans的配置
<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" xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd ">
配置事务管理器
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
<aop:config proxy-target-class="true">
<aop:pointcut id="transactionPointcut"
expression="execution(* service.impl.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcut" />
</aop:config>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="del*" propagation="REQUIRED" />
<tx:method name="*" rollback-for="Exception"/>
</tx:attributes>
</tx:advice>
aop后的属性 proxy-target-class=”true” 默认为false 为jdk动态代理,变为true后为CGLIB代理,如果在测试的时候没有设置这个属性并且在使用getbean方法的时候直接强制装换为实现类而不是接口会报$Proxy4 cannot be cast to的错,解决的办法有两种一是配置属性为true,二是强制装换为接口,当测试类没有实现某个接口时默认用CGLIB代理,不会出现$Proxy4的错,在tx中可以设置对于异常的配置默认rollback-for为RuntimeException,所以这里需要设置对于异常的控制。
方法二:
配置事务管理器
<!-- 事务管理器配置 -->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 使用annotation定义事务 -->
<tx:annotation-driven transaction-manager="txManager"
proxy-target-class="true" />
@Transactional(rollbackFor=Exception.class)
public class CustServImpl implements ICustServ {
private CustInfoDAO custInfoDao;
public CustInfoDAO getCustInfoDao() {
return custInfoDao;
}
public void setCustInfoDao(CustInfoDAO custInfoDao) {
this.custInfoDao = custInfoDao;
}
public void addCust(String name) throws Exception {
// TODO Auto-generated method stub
CustInfo cust = new CustInfo();
cust.setName(name);
//deleteCust("2");
custInfoDao.save(cust);
throw new Exception("custADD测试专用");
}
}
直接在使用该类的最前方配置事务,那么下面的方法都会有相同的配置,也可以对某个单独的方法配置不同的事务。
注意要点:
1. 在抛异常的时候如果使用try catch 方法的话会把异常吞掉,会捕捉不到异常
2. proxy-target-class="true",这个属性默认值为false,使用JDK动态代理,设置为true后卫GCLIB代理,此时可以使用BlogServImpl blogServ = (BlogServImpl) appContext.getBean("BlogServImpl"); 否则不能,只可以使用接口类型强制装换IBlogServ iblog = (IBlogServ) appContext.getBean("BlogServImpl");