SpringFramework中的注解声明式事务怎么被Shiro搞失效了

本文探讨了在Spring Framework中,当使用Shiro时,注解声明式事务为何失效的问题。通过分析代码和运行流程,发现由于Shiro在Spring应用启动时提前创建Realm,导致依赖的Service未经过事务代理。解决方案是使用@Lazy注解延迟初始化Service,以确保事务管理生效。文章还深入解析了Shiro提早创建Realm的原因和@Lazy注解的工作原理。
摘要由CSDN通过智能技术生成

复制代码

resources 目录下创建 sql 文件夹,并创建两个 .sql 文件,分别声明数据库表的结构和数据:

create table if not exists sys_department (

id varchar(32) not null primary key,

name varchar(32) not null

);


insert into sys_department (id, name) values (‘idaaa’, ‘testaaa’);

insert into sys_department (id, name) values (‘idbbb’, ‘testbbb’);

insert into sys_department (id, name) values (‘idccc’, ‘testccc’);

insert into sys_department (id, name) values (‘idddd’, ‘testddd’);

复制代码

[](()编写测试代码

下面就可以按照三层架构来写一些很简单的测试代码了。

[](()DemoDao

这里咱就不整合 MyBatis / Hibernate 了,直接使用原生的 JdbcTemplate 就可以:

@Repository

public class DemoDao {

@Autowired

JdbcTemplate jdbcTemplate;

public List

[](()DemoService + DemoService2

声明一个会触发抛出运行时异常的方法,并标注 @Transactional 注解:

@Service

public class DemoService {

@Autowired

DemoDao demoDao;

@Transactional(rollbackFor = Exception.class)

public void doTransaction() {

demoDao.save(“aaaaaaaa”);

int i = 1 / 0;

demoDao.update(“18”, “ccc”);

}

}

复制代码

DemoService2 同样的代码,仅仅是类名不同,代码不再贴出。

[](()DemoController

Controller 里面同时依赖这两个 Service :

@RestController

public class DemoController {

@Autowired

DemoService demoService;

@Autowired

DemoService2 demoService2;

@GetMapping(“/doTransaction”)

public String doTransaction() {

demoService.doTransaction();

return “doTransaction”;

}

@GetMapping(“/doTransaction2”)

public String doTransaction2() {

demoService2.doTransaction();

return “doTransaction2”;

}

}

复制代码

[](()Realm依赖Service

最后&#x

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值