spring AOP 配置事务不起作用的问题(用Junit测试service)
今天遇到个很怪的事情,在Spring的配置文件中配置好了事务,对Service层所有方法的事务,但对其中一个方法进行测试的时候,发现它并不是个事务,里面的第一步操作完成,第二步操作却失败。找了下原因,原来是在此方法内部,用了try,catch语句块,这样,在内部就把异常给捕捉到了。而Spring中事务回滚是要靠异常来触发的。也就是说,servcie层方法内部不能对异常进行捕获,要向上抛,或者不写(也是抛出了异常),这样,Spring的事务才会起作用。
在Spring的配置文件中如下:
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes> www.zzzyk.com
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="productServiceMethods" expression="execution(public * com.sq.hps.modules.*.service..*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="productServiceMethods"/>
</aop:config>
可以用Junit进行测试:
public class UserTest {
@Test
public void testAddBackRole(){
BackRole backRole = new BackRole();
backRole.setName("test11");
backRole.setDescription("test");
backRole.setParkingIds("");
String privilegeStr = "";
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService)ctx.getBean("userService");
System.out.println(userService);
userService.addBackRole(backRole, privilegeStr);
}
}
补充:软件开发 , Java ,