使用spring AOP 来添加事务

我这里使用是mybatis作为例子

需要引用:aspectjweaver.jar

 

1、spring配置文件

 

<!-- 数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
	<property name="driverClassName">
		<value>com.mysql.jdbc.Driver</value>
	</property>
	<property name="url">
		<!-- <value>jdbc:mysql://127.0.0.1:3306/myspring</value> -->

		<value>jdbc:mysql://172.16.14.81:3306/myspring</value>
	</property>
	<property name="username">
		<value>root</value>
	</property>
	<property name="password">
		<value>admin</value>
	</property>
</bean>

<!-- 指明操作数据库的配置文件位置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	<property name="dataSource" ref="dataSource"></property>
	<property name="configLocation"
		value="classpath:../config/mybatis/MyBatis-Configuration.xml"></property>
</bean>

<!-- 使用事物处理 -->
<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>
		<!-- 定义所有tx打头的方法使用事务 -->
		<tx:method name="add*" rollback-for="Exception" />
		<tx:method name="del*" rollback-for="Exception" />
		<!-- 定义其他方法都是只读 -->
		<tx:method name="*" read-only="true" />
	</tx:attributes>
</tx:advice>

<!-- 定义AOP配置 -->
<aop:config>
	<!-- 定义一个切入点 -->
	<aop:pointcut id="testMethod" expression="execution(* adtec.userManager.service.imp.*.*(..))" />
	<!-- 对切入点和事务的通知,进行适配 -->
	<aop:advisor advice-ref="txAdvice" pointcut-ref="testMethod" />
</aop:config>  

<bean id="userService" class="adtec.userManager.service.imp.UserManagerServiceImpl">  
    <property name="userdao" ref="userDao"></property>  
</bean> 

<bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
	<property name="mapperInterface" value="adtec.userManager.dao.UserDao"></property>
	<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>

 

 

2、MyBatis-Configuration.xml内容

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <mappers>
    	<mapper resource="adtec/userManager/dao/UserDao.xml"/>
    </mappers>
</configuration>

 

3、UserDao.xml内容

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="adtec.userManager.dao.UserDao">
	<resultMap type="adtec.userManager.model.User"
		id="querys">
		<id property="Uid" column="Uid"></id>
		<result property="userName" column="userName"></result>
		<result property="userPassword" column="userPassword"></result>
	</resultMap>


	<!-- 添加新用户 -->
	<insert id="insert" parameterType="adtec.userManager.model.User">
		insert into user(userName,userPassword)
		values(#{userName},#{userPassword})
	</insert>

</mapper>

 

4、service层控制事务

public class UserManagerServiceImpl implements UserManagerService {
	
	Logger log = Logger.getLogger(UserManagerServiceImpl.class);

	private UserDao userdao;
	
	public UserDao getUserdao() {
		return userdao;
	}

	public void setUserdao(UserDao userdao) {
		this.userdao = userdao;
	}

	/**
	 * 用户添加方法
	 */
	@Override
	public boolean add(User user) throws Exception{
		try{
			this.userdao.insert(user);
			Integer.parseInt("d");
			
			log.debug("this.userdao.insert(user)  ok");
		}catch(Exception e){
			log.error("this.userdao.insert(user)  error");
			throw e;
		}
		return true;
	}
	
}

 

备注:

1、这里一定要throw e,不然controller无法知道是否出现异常。

2、方法一定要声明是抛出异常,否则如果直接throw e,则会出现后台错误,事务就无法捕获异常,依然不会回滚。service层操作数据库就会使用try...catch,这样编译器就会帮我们检查代码,是否有捕获异常。

 

controller方法控制的代码

@RequestMapping(value = "/insertAction", method = RequestMethod.POST)
public String AddRegisterAction(HttpServletRequest request,
		HttpServletResponse response) {
	String userName = request.getParameter("userName");
	String userPassword = request.getParameter("userPassword");
	log.debug("AddRegisterAction : "+userName+ ":" + userPassword);
	//将密码进行MD5加密
	String userPasswordMd5 = Md5Util.getMD5String(userPassword);
	User user = new User();
	user.setUserName(userName);
	user.setUserPassword(userPasswordMd5);
	try {
		userService.add(user);
	} catch (Exception e) {
		log.error("添加用户失败");
	}
	//添加后的跳转提示
	String PromptMsg = "InsertMsg";
	
	//跳转到登陆页面
	return "redirect:/user/list.do?PromptMsg="+PromptMsg;
}

 

备注:controller层需要对事务数据库的操作要try...catch,捕获出现的异常,否则会报错,无法跳转到指定的页面

你可能感兴趣的:(spring aop)