---
title: "使用Spring的声明式事务----AOP方式 "
author: "tonlion2046"
date: "2014-07-17T17:35:59Z"
tags: ["Java", "Spring", "声明式事务"]
categories: ["编程语言"]
slug: "spring-aop"
draft: false
lastmod: "2014-07-17T17:39:21Z"
id: 2093314
url: "https://tonl.iteye.com/blog/2093314"
---

类似于上一篇日志，这里使用AOP的方式来配置。

工程结构：

![](http://dl2.iteye.com/upload/attachment/0099/2409/b200c6b7-a1c4-3184-ab59-a75313f8f594.jpg)

大部分代码跟上一个工程类似。

 

服务类StudentService.java代码如下：

```
package com.mysrc.service;

import java.sql.Date;
import java.util.List;

import com.mysrc.dao.StudentDao;
import com.mysrc.entity.Student;

public class StudentService {
	private StudentDao dao;

	public void setDao(StudentDao dao) {
		this.dao = dao;
	}

	public void doComplexLogic() {

		// select
		List<Student> list = dao.getAllStudent();
		for (Student student : list) {
			System.out.println(student);
		}

		// update
		Student student = list.get(0);
		student.setName("laohu..");
		dao.updateStudent(student);
		System.out.println("did update temporarily...");

		//int a = 9 / 0; // 遇到异常，整个事务回滚，也即上面的update不会成功
		// 如果try catch捕获这个异常，那整个事务会顺利执行，不会回滚
		
		int b = 2;
		if (b > 1) {
			throw new CustomRuntimeException();
			// 事务不会回滚，也就是上面的update操作会提交
		}

		// insert
		student = new Student();
		student.setName("hello");
		student.setBirth(new Date(354778));
		student.setScore(78.9f);
		dao.addStudent(student);
		System.out.println("did insert...");

		// delete
		dao.deleteStudent(3);
		System.out.println("did delete...");
	}

}
```

 这里doComplexLogic()方法上不再有注解修饰了。

 

Spring的应用程序上下文配置文件applicationContext.xml的内容为：

```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/aop   
    http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx.xsd"
	xmlns:tx="http://www.springframework.org/schema/tx">

	<bean id="basicDataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="url"
			value="jdbc:mysql://127.0.0.1:3306/mytestdb?characterEncoding=utf8" />
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="username" value="root" />
		<property name="password" value="123456" />
		<property name="maxActive" value="100" />
		<property name="maxIdle" value="30" />
		<property name="maxWait" value="1000" />
		<property name="validationQuery" value="select 1" />
	</bean>
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<constructor-arg name="dataSource" ref="basicDataSource">
		</constructor-arg>
	</bean>
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager ">
		<property name="dataSource">
			<ref bean="basicDataSource" />
		</property>
	</bean>

	<bean id="studentDao" class="com.mysrc.dao.StudentDao">
		<property name="jdbcTemplate">
			<ref bean="jdbcTemplate" />
		</property>
	</bean>

	<bean id="studentService" class="com.mysrc.service.StudentService">
		<property name="dao">
			<ref bean="studentDao" />
		</property>
	</bean>

	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="add*" propagation="REQUIRED" />
			<tx:method name="del*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="get*" propagation="NOT_SUPPORTED"
				read-only="true" />
			<tx:method name="doComplexLogic" propagation="NESTED"
				isolation="REPEATABLE_READ" timeout="1000" rollback-for="java.lang.Exception"
				no-rollback-for="com.mysrc.service.CustomRuntimeException" />
		</tx:attributes>
	</tx:advice>

	<!-- Spring AOP config -->
	<aop:config>
		<!-- 切入点 -->
		<aop:pointcut id="studentServicesPointcut"
			expression="execution(* com.mysrc.service.StudentService.*(..))" />
		<!-- <aop:pointcut id="newServicesPointcut2" expression="execution(* com.model.*.*(..))" 
			/> -->
		<aop:advisor advice-ref="txAdvice" pointcut-ref="studentServicesPointcut" />
		<!-- <aop:advisor advice-ref="txAdvice" pointcut-ref="newServicesPointcut2" 
			/> -->
	</aop:config>

</beans>
```

   
 整个eclipse工程文件在附件中。。