当前位置: 首页 > news >正文

Spring事务管理:@Transactional注解深度解析

Spring事务管理:@Transactional注解深度解析

Spring框架是Java后端开发的核心技术栈,掌握其原理和最佳实践至关重要。

一、Spring核心特性

事务管理是企业级应用的核心功能,理解Spring事务的传播行为和隔离级别对保证数据一致性至关重要

二、IOC容器

2.1 Bean的生命周期

Spring Bean 生命周期流程:

实例化↓
属性赋值 (populateBean)↓
BeanNameAware (setBeanName)↓
BeanFactoryAware (setBeanFactory)↓
ApplicationContextAware (setApplicationContext)↓
BeanPostProcessor前置 (postProcessBeforeInitialization)↓
InitializingBean (afterPropertiesSet)↓
init-method (自定义初始化方法)↓
BeanPostProcessor后置 (postProcessAfterInitialization)↓
使用Bean (ready for use)↓
DisposableBean (destroy)↓
destroy-method (自定义销毁方法)

说明:
- 蓝色节点:Spring 提供的扩展接口
- 绿色节点:用户自定义的方法

2.2 依赖注入方式

// 1. 构造器注入(推荐)
@Component
public class UserService {private final UserRepository userRepository;@Autowiredpublic UserService(UserRepository userRepository) {this.userRepository = userRepository;}
}// 2. Setter注入
@Component
public class UserService {private UserRepository userRepository;@Autowiredpublic void setUserRepository(UserRepository userRepository) {this.userRepository = userRepository;}
}// 3. 字段注入(不推荐)
@Component
public class UserService {@Autowiredprivate UserRepository userRepository;
}

三、AOP面向切面编程

3.1 AOP核心概念

  • 切面(Aspect):横切关注点的模块化
  • 连接点(JoinPoint):程序执行的某个位置
  • 切点(Pointcut):匹配连接点的表达式
  • 通知(Advice):在切点上执行的动作
  • 目标对象(Target):被代理的对象

3.2 通知类型

@Aspect
@Component
public class LoggingAspect {// 前置通知@Before("execution(* com.example.service.*.*(..))")public void beforeMethod(JoinPoint joinPoint) {System.out.println("Before: " + joinPoint.getSignature());}// 后置通知@After("execution(* com.example.service.*.*(..))")public void afterMethod(JoinPoint joinPoint) {System.out.println("After: " + joinPoint.getSignature());}// 返回通知@AfterReturning(pointcut = "execution(* com.example.service.*.*(..))",returning = "result")public void afterReturning(JoinPoint joinPoint, Object result) {System.out.println("AfterReturning: " + result);}// 异常通知@AfterThrowing(pointcut = "execution(* com.example.service.*.*(..))",throwing = "ex")public void afterThrowing(JoinPoint joinPoint, Exception ex) {System.out.println("AfterThrowing: " + ex.getMessage());}// 环绕通知@Around("execution(* com.example.service.*.*(..))")public Object aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {System.out.println("Around Before");Object result = joinPoint.proceed();System.out.println("Around After");return result;}
}

四、Spring事务管理

4.1 事务注解

@Service
public class OrderService {// 声明式事务@Transactional(propagation = Propagation.REQUIRED,  // 传播行为isolation = Isolation.READ_COMMITTED,  // 隔离级别timeout = 30,  // 超时时间readOnly = false,  // 只读rollbackFor = Exception.class  // 回滚异常)public void createOrder(Order order) {// 业务逻辑}
}

4.2 事务传播行为

传播行为 说明
REQUIRED 默认,如果存在事务则加入,否则新建
REQUIRES_NEW 新建事务,挂起当前事务
SUPPORTS 如果存在事务则加入,否则非事务执行
NOT_SUPPORTED 非事务执行,挂起当前事务
MANDATORY 必须在事务中,否则抛异常
NEVER 必须非事务执行,否则抛异常
NESTED 嵌套事务,回滚点保存

五、Spring Boot自动配置

5.1 自动配置原理

// @EnableAutoConfiguration 注解
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {String[] excludeName() default {};
}// 自动配置类示例
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(DataSource.class)
@ConditionalOnProperty(prefix = "spring.datasource", name = "url")
@EnableConfigurationProperties(DataSourceProperties.class)
public class DataSourceAutoConfiguration {// 配置逻辑
}

5.2 常用注解

// 条件注解
@ConditionalOnClass        // 类路径下存在指定类
@ConditionalOnMissingClass  // 类路径下不存在指定类
@ConditionalOnBean         // 容器中存在指定Bean
@ConditionalOnMissingBean   // 容器中不存在指定Bean
@ConditionalOnProperty      // 配置属性满足条件
@ConditionalOnWebApplication  // Web环境

六、常见面试题

Q1: Spring中循环依赖如何解决?

答案:
Spring通过三级缓存解决循环依赖:

// 三级缓存
1. singletonObjects          // 一级缓存:完整的Bean
2. earlySingletonObjects     // 二级缓存:提前暴露的Bean
3. singletonFactories        // 三级缓存:Bean的工厂// 解决流程
1. A实例化后,放入三级缓存
2. A注入B,B需要A
3. B从三级缓存获取A的工厂,创建A的代理对象
4. B注入A的代理对象,B完成初始化
5. A继续初始化,注入B,完成初始化

Q2: @Autowired和@Resource的区别?

答案:

特性 @Autowired @Resource
来源 Spring Java JSR-250
匹配方式 按类型,其次按名称 按名称,其次按类型
Required属性 支持 不支持
作用位置 构造器、方法、字段 方法、字段

Q3: 事务失效的场景有哪些?

答案:
1. 方法不是public
2. 方法自调用(this调用)
3. 异常被捕获未抛出
4. 异常类型不匹配(默认RuntimeException)
5. 数据库引擎不支持事务
6. 未被Spring管理(无@Component等注解)

七、最佳实践

代码规范:
- 优先使用构造器注入
- 合理使用AOP,避免过度设计
- 事务粒度要小,避免大事务

性能优化:
- 使用循环依赖缓存
- 合理使用懒加载(@Lazy)
- 控制Bean的生命周期

八、总结

Spring框架博大精深,持续学习:

核心要点
- 掌握IOC和AOP原理
- 理解事务传播机制
- 熟悉自动配置原理

进阶方向
- 阅读Spring源码
- 学习Spring Cloud微服务
- 实践项目应用

推荐资源
- 《Spring实战》
- Spring官方文档
- Spring源码分析


http://www.jsqmd.com/news/397407/

相关文章:

  • 读懂大模型:写给AI团队新人的技术指南,非常详细收藏这一篇就够了
  • 常用算法代码模板及代码技巧
  • 7大AI论文改写网站实测:排名与技巧一网打尽。
  • 6个角度彻底搞懂智能体,小白也能轻松入门大模型
  • Gemini 3.1 Pro 大模型学习指南,收藏这份进阶秘籍
  • 7款AI论文网站排名+改写技巧,科研党必看指南。
  • 高效论文写作:7款AI工具排名与核心技巧解析。
  • 从改写工具到网站排名:7款AI论文写作全攻略。
  • IDEA内置Maven的本地仓库路径说明
  • 代码智能分析:质量提升方案
  • AI总结日志,我的天把我都吓到了
  • 伦理量子信息学:九元原子的量子信息实现
  • 从春晚聚光灯到城市基本盘,NAVEE Commercial如何编织全球出行“路网”?
  • 精选7款AI论文写作网站,高效技巧与排名全解析!
  • 【超全】基于微信小程序的体育场管理系统【包括源码+文档+调试】
  • researchgate无法打开,这是什么原因?
  • 装了cl云之后,邮箱都无法显示了,为何?
  • 【超全】基于微信小程序的图书阅读平台【包括源码+文档+调试】
  • 7大AI论文工具实测:改写技巧与网站排名指南。
  • 7款AI论文工具深度评测:改写技巧与权威排名。
  • AI论文写作必备:7款网站排名与实用改写技巧。
  • 基于AI原生应用领域思维树的创新解决方案
  • 实测有效的9个AI降重平台:文本改写准确率达92%以上,智能优化语句结构,快速生成无重复内容
  • 意想不到,已经开始反哺语言了!
  • 大数据治理基石:如何构建高效的数据目录系统?
  • 题解:AcWing 800 数组元素的目标和
  • 传统降重太耗时?这9个AI网站10秒完成高质量改写,语义保留度超95%,效率提升20倍
  • 从数据到创意:集体好奇心助力团队突破
  • 题解:AcWing 2816 判断子序列
  • A.inverse ()*B 表示从 A 到 B 的变换