除了下面的两个部分有变化,其他的和前面的配置方式实现的一样
xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--
基于注解的方式实现spring事务的配置
-->
<!-- 扫描包配置 -->
<context:component-scan base-package="com.self.spring.*"/>
<!-- 配置加载属性参数 -->
<context:property-placeholder location="db.properties"/>
<!-- 配置数据源 -->
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
<property name="url" value="${jdbc_url}"/>
<property name="driverClassName" value="${jdbc_driver}"/>
<property name="password" value="${jdbc_password}"/>
<property name="username" value="${jdbc_username}"/>
</bean>
<!-- 配置jdbcTemplate -->
<bean class="org.springframework.jdbc.core.JdbcTemplate" primary="true">
<constructor-arg name="dataSource" ref="dataSource"/>
</bean>
<!-- 事务配置 -->
<!-- 事务管理器 ,针对数据库的-->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 开启事务注解支持 -->
<tx:annotation-driven transaction-manager="txManager"/>
</beans>
service层:
package com.self.spring.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.self.spring.dao.IUserDao;
import com.self.spring.pojo.User;
import com.self.spring.service.IUserService;
/** 基于注解方式的事务的操作
*
* @ClassName:UserServiceImpl_Annotation
* @Description:TODO
* @author guanjun.zhou
* @data: 2020-12-2417:25:49
*/
@Service
@Primary//表示优先加载该类
public class UserServiceImpl_Annotation implements IUserService {
@Autowired
private IUserDao dao;
@Override
//事务操作方法
public Integer addUser(User user) {
System.out.println("添加成功。。。");
return dao.addUser(user);
}
@Override
public Integer updata(User user) {
return dao.update(user);
}
@Transactional//开始事务管理
public Integer business() {
User user=new User(9,"小子",558);
addUser(user);
user.setId(5);
user.setUserName("张铁柱");
user.setMoney(8988);
return updata(user);
}
}