在讲到SpringAOP的时候,我们是自己去增强事务控制,而这些功能,Spring框架都为我们准备好了,而我们只要去使用就可以了。当然,也别觉得SrpingAOP就只有增强事务的功能,只要是想要增强的方法都可以使用AOP去增强。那么我们怎么去使用呢?
XML配置声明式事务
spring中基于XML的声明式事务控制配置步骤
1.配置事务管理器
2.配置事务的通知
此时我们需要导入事务的约束 tx名称空间和约束,同时也需要aop的
使用<tx:advice>标签配置事务通知
属性:
id:给事务通知起一个唯一标识
transaction-manager:给事务通知提供一个事务管理器引用
3.配置aop中的通用切入点表达式
4.建立事务通知和切入点表达式的关系
使用<aop:advisor>标签
属性:pointcut-ref:用于引用配置的切入点表达式
advice-ref:用于引用事务通知
5.配置事务的属性
是在事务的通知<tx:advice>标签的内部
isolation:用于指定事务的隔离级别,默认级别DEFAULT,表示使用数据库的默认隔离级别
propagation:用于指定事务的传播行为。默认值是REQUIRED,表示一定会有事务,增删改的选择。查询方法可以选择SUPPORTS
read-only:用于指定事务是否只读,只有查询方法才能设置为true。默认值是false,表示读写
timeout:用于指定事务的超时时间,默认值是-1,表示永不超时。如果制定了数值,以秒为单位
rollback-for:用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚。没有默认值。表示任何异常都回滚
no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时,事务回滚。没有默认值。表示任何异常都回滚
XML配置事务案例(使用JdbcTemplate的案例)
IAccountDao接口类
package com.dao;
import com.domain.Account;
//账户的持久层接口
public interface IAccountDao {
Account findAccountById(int id);
Account findAccountByName(String name);
void updateAccount(Account account);
}
IAccountDao实现类
package com.dao.impl;
import com.dao.IAccountDao;
import com.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
//账户的持久层实现类
public class AccountDaoImpl implements IAccountDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public Account findAccountById(int id) {
List<Account> accountList = jdbcTemplate.query("select * from account where id = ?" , new BeanPropertyRowMapper<Account>(Account.class) , id);
return accountList.isEmpty()? null : accountList.get(0);
}
public Account findAccountByName(String name) {
List<Account> accountList = jdbcTemplate.query("select * from account where name = ? " , new BeanPropertyRowMapper<Account>(Account.class) , name);
if(accountList.isEmpty()){
return null;
}
if(accountList.size() > 1){
throw new RuntimeException("结果集不唯一");
}
return accountList.get(0);
}
public void updateAccount(Account account) {
jdbcTemplate.update("update account set name = ? , money = ? where id = ?" , account.getName() , account.getMoney() , account.getId());
}
}
IAccountService接口类
package comservice;
import com.domain.Account;
public interface IAccountService {
Account findAccountById(Integer id);
void transfer(String sourceName , String targetName , Float money);
}
IAccountService实现类
package com.service.impl;
import com.dao.IAccountDao;
import com.domain.Account;
import com.service.IAccountService;
import java.util.List;
//账户的业务层实现类
//事务的控制都是在业务层的
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
public Account findAccountById(Integer id) {
Account accounts = accountDao.findAccountById(id);
return accounts;
}
public void updateAccount(Account account) {
accountDao.updateAccount(account);
}
public void transfer(String sourceName, String targetName, Float money) {
System.out.println("转账正在进行");
//1.根据名称查询转出账户
Account source = accountDao.findAccountByName(sourceName);
//2.根据名称查询转入账户
Account target = accountDao.findAccountByName(targetName);
//3.转出账户减钱
source.setMoney(source.getMoney() - money);
//4.转入账户加钱
target.setMoney(target.getMoney() + money);
//5.更新转出账户
accountDao.updateAccount(source);
//int i =1/0;
//6.更新转入账户
accountDao.updateAccount(target);
}
}
bean.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
配置事务管理器
<!--配置事务管理器-->
<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:method name="*" propagation="REQUIRED" read-only="false"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"></tx:method>
</tx:attributes>
</tx:advice>
配置AOP同时建立切入点表达式和事务通知的对应关系(详细的解释在开头过程讲解中)
<aop:config>
<!--配置切入点表达式-->
<aop:pointcut id="pointCut" expression="execution(* com.itheima.service.impl.*.*(..))"></aop:pointcut>
<!--建立切入点表达式和事务通知的对应关系-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut"></aop:advisor>
</aop:config>
测试类
package com.test;
import com.service.IAccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
//使用Junit单元测试我们的配置
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
@Autowired
private IAccountService as;
@Test
public void testTransfer(){
as.transfer("aaa" , "bbb" , 200f);
}
}
无异常时:
运行后:
出现异常时:
将在transfer方法中的int i =1/0
注释关闭。
运行后:
可以发现事务控制已经增强进了切入点方法中。至此,声明式事务基于XML配置就完成了。
注解配置声明式事务
spring中与注解的声明式事务控制配置步骤
1.配置事务管理器
2.开启spring注解事务的支持
3.在需要事务支持的地方使用@Transactional注解
注意:在此次过程中采用纯注解方式
新建jdbcConfig.properties属性配置文件
其中存放的信息是创建数据源所需要的。
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=
新建IAccountDao
package com.dao;
import com.domain.Account;
//账户的持久层接口
public interface IAccountDao {
Account findAccountById(int id);
Account findAccountByName(String name);
void updateAccount(Account account);
}
新建IAccountDao实现类
package com.dao.impl;
import com.dao.IAccountDao;
import com.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
//账户的持久层实现类
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public Account findAccountById(int id) {
List<Account> accountList = jdbcTemplate.query("select * from account where id = ?" , new BeanPropertyRowMapper<Account>(Account.class) , id);
return accountList.isEmpty()? null : accountList.get(0);
}
public Account findAccountByName(String name) {
List<Account> accountList = jdbcTemplate.query("select * from account where name = ? " , new BeanPropertyRowMapper<Account>(Account.class) , name);
if(accountList.isEmpty()){
return null;
}
if(accountList.size() > 1){
throw new RuntimeException("结果集不唯一");
}
return accountList.get(0);
}
public void updateAccount(Account account) {
jdbcTemplate.update("update account set name = ? , money = ? where id = ?" , account.getName() , account.getMoney() , account.getId());
}
}
新建IAccountService接口类
package com.service;
import com.domain.Account;
public interface IAccountService {
Account findAccountById(Integer id);
void transfer(String sourceName , String targetName , Float money);
}
新建IAccountService实现类
package com.service.impl;
import com.dao.IAccountDao;
import com.domain.Account;
import com.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
//账户的业务层实现类
//事务的控制都是在业务层的
@Service
//此标签表示需要事务支持,主有此注解的类才会开启事务
@Transactional
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
public Account findAccountById(Integer id) {
Account accounts = accountDao.findAccountById(id);
return accounts;
}
public void updateAccount(Account account) {
accountDao.updateAccount(account);
}
public void transfer(String sourceName, String targetName, Float money) {
System.out.println("转账正在进行");
//1.根据名称查询转出账户
Account source = accountDao.findAccountByName(sourceName);
//2.根据名称查询转入账户
Account target = accountDao.findAccountByName(targetName);
//3.转出账户减钱
source.setMoney(source.getMoney() - money);
//4.转入账户加钱
target.setMoney(target.getMoney() + money);
//5.更新转出账户
accountDao.updateAccount(source);
//int i =1/0;
//6.更新转入账户
accountDao.updateAccount(target);
}
}
新建JdbcConfig配置类
package config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
//和连接数据库相关的配置类
@Configuration//配置类标签
@ComponentScan//在加入容器时需要扫描的包
public class JdbcConfig {
//Value标签为给变量赋值,而其中的EL表达式使用${}引用外部文件的值,这里表示引用属性文件中的值。
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
//Bean标签为将返回值对象存入容器中
@Bean(name="jdbcTemplate")
public JdbcTemplate createJdbcTemplate(DataSource dataSource){
return new JdbcTemplate(dataSource);
}
//Bean标签为将返回值对象存入容器中
@Bean(name="dataSource")
public DataSource createDataSource(){
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setDriverClassName(driver);
driverManagerDataSource.setUrl(url);
driverManagerDataSource.setUsername(username);
driverManagerDataSource.setPassword(password);
return driverManagerDataSource;
}
}
新建事务配置类TransactionManagerConfig
package config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
//配置类标签
@Configuration
public class TransactionManagerConfig {
//Bean标签为将返回值对象存入容器中
@Bean(name="transactionManager")
public PlatformTransactionManager createTransactionManager(DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
}
新建SpringConfiguration配置类(相当于bean.xml)
package config;
import org.springframework.context.annotation.*;
import org.springframework.transaction.annotation.EnableTransactionManagement;
//spring的配置类
@Configuration//表示是配置类
@ComponentScan("com")//在新建容器时,需要扫描的包
@Import({JdbcConfig.class , TransactionManagerConfig.class})//此配置类是主配置类,如果需要引用其他配置类,需要用Import标签引入。属性为配置类的字节码。
@PropertySource("jdbcConfig.properties")//此标签为引入属性配置文件
@EnableTransactionManagement//开启事务控制
@EnableAspectJAutoProxy//允许开启AOP为注解模式
public class SpringConfiguration {
}
新建测试类
package com.test;
import com.service.IAccountService;
import config.SpringConfiguration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
//使用Junit单元测试我们的配置
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
@Autowired
private IAccountService as;
@Test
public void testTransfer(){
as.transfer("aaa" , "bbb" , 500f);
}
}
测试结果
数据库原始数据:
没有出现异常时:
转账功能正常
出现异常时(在transfer方法中打开int i = 1/0的注解):