【全注解第一步】添加Spring事务管理注解【该注解添加在业务逻辑层的 接口实现类 或者 接口实现类的方法上,而不能放在接口上】
public interface AccountService {
//配置当前接口方法具有事务
@Transactional
public void transfer(String out,String in,Double money) ;
}
//注意: @Transactional 该注解放在方法上那么作用范围就是这个方法,
如果放在类上,那么做作用范围就是类中的所有方法。
注意事项
Spring注解式事务通常添加在业务层接口中而不会添加到业务层实现类中,降低耦合
注解式事务可以添加到业务方法上表示当前方法开启事务,也可以添加到 接口实现类 上表示当前类中所有方法开启事务
【全注解第二步】设置事务管理器(将事务管理器添加到IOC容器中)
说明:可以在JdbcConfig中配置事务管理器
//配置事务管理器
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource){
DataSourceTransactionManager dtm = new DataSourceTransactionManager();
dtm.setDataSource(dataSource);
return dtm;
}
注意事项:
1. 事务管理器要根据实现技术进行选择
2. MyBatis框架使用的是JDBC事务
【全注解第三步】开启注解式事务驱动
@Configuration
@ComponentScan("com.powernode.bank")
@EnableTransactionManagement //开启事务注解驱动
public class Config {
@Bean
public DataSource dataSource(){
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
druidDataSource.setUrl("jdbc:mysql://localhost:3306/spring6?serverTimezone=UTC&");
druidDataSource.setUsername("root");
druidDataSource.setPassword("123456");
return druidDataSource;
}
@Bean
public JdbcTemplate jdbcTemplate(){
return new JdbcTemplate(dataSource());
}
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource){
DataSourceTransactionManager dtm = new DataSourceTransactionManager();
dtm.setDataSource(dataSource);
return dtm;
}
}
【基于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" <!--添加context命名空间-->
xmlns:tx="http://www.springframework.org/schema/tx" <!--添加tx(transaction)命名空间-->
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 <!--添加context命名空间-->
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd<!--添加tx(transaction)命名空间-->">
<!--扫描组件-->
<context:component-scan base-package="com.powernode.bank"/>
<!--配置数据源-->
<bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/spring6"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--配置JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="druidDataSource"></property>
</bean>
<!--配置事务管理器-->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="druidDataSource"/>
</bean>
<!--开启事务注解驱动器-->
<tx:annotation-driven transaction-manager="txManager"/>
</beans>
注意。使用xml配置的话,也需要添加S pring事务管理注解 @Transactional