spring内置了事务管理器,来支持spring的事务管理。同时,spring的事务控制,也可以通过AOP的配置来完成。
1、基于xml的事务配置
导入pom坐标:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
创建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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--<!–配置账户持久层–>-->
<!--<bean id="accountDapImpl" class="com.yunxiao.dao.impl.AccountDaoImpl">-->
<!--<property name="jdbcTemplate" ref="template"></property>-->
<!--</bean>-->
<context:component-scan base-package="com.yunxiao"></context:component-scan>
<bean id="accountDapImpl2" class="com.yunxiao.dao.impl.AccountDaoImpl2">
<!--<property name="jdbcTemplate" ref="template"></property>-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--<bean id="template" class="org.springframework.jdbc.core.JdbcTemplate">-->
<!--<property name="dataSource" ref="dataSource"></property>-->
<!--</bean>-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/eesy"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!--配置业务层对象-->
<bean id="accountService" class="com.yunxiao.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDapImpl2"></property>
</bean>
<!--spring中基于xml声明式事务控制步骤
1、配置事务管理器
2、配置事务通知
此时需要导入事务的约束,需要导入tx和aop的约束
使用tx:advice标签
属性:id唯一标示,transaction-manager给事务通知配置一个事务管理器
3、配置AOP中的切入点表达式
4、建立事务通知和切入点表达式的关系
5、配置事务的属性
5.1在事务的通知tx:advice标签内部使用tx:method
属性:name表示事务通知的方法,*表示匹配所有的方法,find表示方法以find开头的方法-->
<!--1、配置spring的事务事务护理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--配置事务的属性
isolation="",用于指定事务的隔离级别,默认是DEFAULT,表示数据库的默认隔离级别
no-rollback-for="",用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时不回滚。没有默认值,表示任何异常都回滚
propagation="",用于指定事务的传播行为,默认值是QEIERED,表示一定会有事务,增删改的选择。查询方法可以用SUPPORTS。
read-only="",用于指定事务是否只读,只有查询方法可以设为ture,默认是false。
rollback-for="",用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时回滚。没有默认值,表示任何异常都不回滚
timeout="",用于指定事务的超时时间,默认值是-1,表示永不超时,如果指定了数值,以秒为单位-->
<tx:attributes>
<tx:method name="transfre" propagation="REQUIRED" read-only="false"/>
<tx:method name="find" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<!--AOP切入点表达式-->
<aop:config>
<aop:pointcut id="pt1" expression="execution(* com.yunxiao.service.impl.*.*(..))"></aop:pointcut>
<!--建立通知和切入点表达式的关系-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
</aop:config>
</beans>
测试
package com.yunxiao;
import com.yunxiao.dao.IAccountDao;
import com.yunxiao.domain.Account;
import com.yunxiao.service.IAccountService;
import com.yunxiao.service.impl.AccountServiceImpl;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author :
* @date :Created in 2020/5/20 下午4:10
* @description:${description}
* @modified By:
* @version: $version$
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml" )
public class TempLateTest {
@Autowired
IAccountService as;
@Test
public void testTransfre(){
as.transfre("美国队长","ccc",500f);
}
@Test
public void testFindByAccountId(){
Account account = as.findByAccountId(2);
System.out.println(account);
}
}
2、基于注解的事务配置
创建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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.yunxiao"></context:component-scan>
<bean id="jdbcTempLate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/eesy"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!--spring中基于z注解声明式事务控制步骤
1、配置事务管理器
2、开启spring对注解事务的支持
3、在需要事务支持的地方使用@Transactional注解-->
<!--1、配置spring的事务事务护理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--开启spring对注解事务的支持-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>
代理类中添加注解
package com.yunxiao.service.impl;
import com.yunxiao.dao.impl.AccountDaoImpl;
import com.yunxiao.dao.impl.AccountDaoImpl2;
import com.yunxiao.domain.Account;
import com.yunxiao.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
/**
* @author :陈文
* @date :Created in 2020/5/21 上午10:31
* @description:${description}
* @modified By:
* @version: $version$
*/
//事务控制应该都在业务层
@Service("accountService")
@Transactional(propagation = Propagation.REQUIRED,readOnly = true)
public class AccountServiceImpl implements IAccountService {
@Autowired
AccountDaoImpl accountDao;
//需要读写型事务配置
@Override
@Transactional(propagation = Propagation.REQUIRED,readOnly = false)
public Account findByAccountId(Integer id) {
return accountDao.findAccountById(id);
}
/**
* sourceName:转出账户名称
* targetName:转入账户名称
* float:转出金额
*/
@Override
public void transfre(String sourceName, String targeName, float money) {
Account source = accountDao.findAccountName(sourceName);
Account targe = accountDao.findAccountName(targeName);
source.setMoney(source.getMoney()-money);
targe.setMoney((targe.getMoney()+money));
accountDao.updateAccount(source);
int i = 1/0;
accountDao.updateAccount(targe);
}
}
3、spring去除xml文件的事务控制
通过类中的注解来创建bean对象,将创建出的对象都叫个spring容器来管理
创建配置(config)类
创建主配置类,主配置类中的@Import注解可以导入其他配置类
package config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @author :
* @date :Created in 2020/5/21 下午2:54
* @description:spring的配置类,相当于bean.xml
* @modified By:
* @version: $version$
*/
@Configuration//表明是一个配置类,主配置类
@ComponentScan("com.yunxiao")//配置扫描的包
@Import({JdbcConfig.class,TransactionConfig.class})//导入其他配置类
@PropertySource(value = "jdbcConfig.properties")//加载配置类
@EnableTransactionManagement//实现对事务注解的支持
public class SpringConfiguration {
}
创建数据库配置类
package config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
/**
* @author :
* @date :Created in 2020/5/21 下午2:57
* @description:和数据库配置相关的类
* @modified By:
* @version: $version$
*/
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
/**
* 创建JdbcTemplate
* @param dataSource
* @return
*/
@Bean(name = "jdbcTemplate")
public JdbcTemplate createJdbcTemplate(DataSource dataSource){
return new JdbcTemplate(dataSource);
}
/**
* 创建DataSource对象
* @return
*/
@Bean(name = "dataSource")
public DataSource createDataSource(){
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
}
创建事务管理器的类:
package config;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
/**
* @author :
* @date :Created in 2020/5/21 下午3:09
* @description:事务相关的配置类
* @modified By:
* @version: $version$
*/
public class TransactionConfig {
/**
* 用于创建事务管理器对象
* @param dataSource
* @return
*/
@Bean(name = "transacionManager")
public PlatformTransactionManager createTransacManager(DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
}