Spring AOP事务控制实战指南

发布时间:2026/7/2 16:15:34

Spring AOP事务控制实战指南 Spring AOP控制事务1 导入依赖?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beans xmlns:contexthttp://www.springframework.org/schema/context xmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xmlns:txhttp://www.springframework.org/schema/tx xmlns:aophttp://www.springframework.org/schema/aop xsi:schemaLocationhttp://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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd配置事务!-- Spring 提供的 JDBC 事务管理器-- bean idtransactionManager classorg.springframework.jdbc.datasource.DataSourceTransactionManager property namedataSource refdataSource/property /bean配置增强!-- 增强要搞的事务 eg事务-- tx:advice idtxAdvice transaction-managertransactionManager tx:attributes tx:method nameget* read-onlytrue propagationSUPPORTS / //查询单条信息 tx:method nameselect* read-onlytrue propagationSUPPORTS / //查询多条信息 tx:method nameinsert* ///默认方式 tx:method namedelete* / tx:method nameupdate* / tx:method name*/ /tx:attributes /tx:advice配置切点!-- 切点切面-- aop:config !-- 切点-- //想要增强的方法 aop:pointcut idpointcut expressionexecution(* com.yunkukukukuku.service.*.*(..))/ !-- 切面-- //txAdvice 事务的id 切点 aop:advisor advice-reftxAdvice pointcut-refpointcut/ /aop:config在测试类当中进行可以看出输出结果userService.getClass()是代理类生成的如果中间失败则会启动回滚事务基于注解的AOP控制事务bean idtransactionManager classorg.springframework.jdbc.datasource.DataSourceTransactionManager property namedataSource refdataSource/property /bean !-- 开启spring对注解事务的支持并指定对应的事务管理器 -- tx:annotation-driven transaction-managertransactionManager/在测试类service当中Transactional 是 Spring 的声明式事务注解作用是功能标记在 Service 类或方法上开启事务管理方法执行成功自动提交事务方法抛出 RuntimeException 自动回滚事务保证数据库操作的原子性和一致性使用的userService 也是代理类生成的

相关新闻