springBoot集成声明式和编程式事务的方式
一、声明式事务
前提集成了mybatisplus插件
1、pom依赖
<dependencies>
<!-- MyBatis-Plus 启动器 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.4</version>
</dependency>
<!-- PostgreSQL 驱动 -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Spring Boot JDBC 起步依赖(内含事务管理器的自动配置) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- 其他依赖 -->
</dependencies>
2、数据源配置
# PostgreSQL 数据源配置
spring.datasource.url=jdbc:postgresql://localhost:5432/your_database
spring.datasource.username=postgres
spring.datasource.password=your_password
spring.datasource.driver-class-name=org.postgresql.Driver
# MyBatis-Plus 配置(可选,根据需要调整)
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
3、启动事务管理
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication
@EnableTransactionManagement
@MapperScan("com.example.mapper") // 扫描你的 Mapper 包路径
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
@MapperScan 不是强制性的,如果你在每个 Mapper 接口上都加了 @Mapper 注解,Spring Boot 也能扫描到它们。不过,使用 @MapperScan 更为集中管理和配置扫描包是比较推荐的做法。
5、手动配置事务管理器(可选)
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
@Configuration
public class TransactionManagerConfig {
@Bean
public DataSourceTransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
测试参考:测试参考代码
6、报错解决
1)循环依赖问题
org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'sysUserService': Bean with name 'sysUserService' has been injected into other beans [sysRoleService] in its raw version as part of a circular reference, but has eventually been wrapped. This means that said other beans do not use the final version of the bean. This is often the result of over-eager type matching - consider using 'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.
原因:这个错误主要是由于在启用事务管理后,Spring 会对带有事务注解的 Bean 进行代理包装,而你的业务中存在循环依赖问题,导致 sysUserService 在被注入到 sysRoleService 时,注入的是原始(raw)的 Bean,而后期又被包装成代理 Bean,从而引发了循环依赖错误。
即:当启用 @EnableTransactionManagement 后,带有 @Transactional 注解的 Bean 会被代理,如果在创建过程中遇到循环依赖,Spring 无法正确处理代理后的 Bean,导致最终注入的 Bean 与预期不符。
解决方案:重构代码取消循环依赖 或者使用懒加载 方式解决。
@Service
public class SysRoleService {
@Autowired
@Lazy
private SysUserService sysUserService;
// 其他方法...
}
2)
7、
8、
二、编程式事务
1、
2、
3、
持续更新中.......