springboot+shiro+mybatis整合发现部分功能事务没有被spring管理

来源:互联网 发布:淘宝商家添加商品 编辑:程序博客网 时间:2024/06/18 15:40

最近写一个后台管理的开源项目,发现报错事务没有回滚,折磨了我两天发现其他功能事务都是好用的,只有关于用户的那部分事务没有被spring管理,最后发现在shiro在启动配置的时候Spring还没启动,因为是Shiro先启动的。

在百度了好久也没解决办法,好多都说直接用dao调用,还有提高spring启动的优先级,这些都试过,没用!!然后Google发现一个靠谱的解决办法。

解决办法:

/** * 声明SecurityManager * @return */@Bean(name="securityManager")public SecurityManager securityManager() {    DefaultWebSecurityManager manager = new DefaultWebSecurityManager();    //manager.setRealm(authorityRealm);    manager.setCacheManager(new MemoryConstrainedCacheManager());    return manager;}
在shiro启动的时候不设置自己的realm,然后在spring启动完成后再设置自己的realm。

所以需要写一个监听器,在spring初始化完成后设置自己的realm就可以了

@Componentpublic class SpringEventListener {    @EventListener    public void handleContextRefresh(ContextRefreshedEvent event) {        ApplicationContext context = event.getApplicationContext();        DefaultWebSecurityManager manager = (DefaultWebSecurityManager) context.getBean("securityManager");        AuthorizingRealm realm = (AuthorizingRealm) context.getBean("authorityRealm");        realm.setCredentialsMatcher(new CustomCredentialsMatcher());        manager.setRealm(realm);    }}




解决办法来源于http://keanu.tumblr.com/post/136866599865/%E8%AE%93-shiro-realm-%E4%B9%9F%E8%83%BD%E4%BD%BF%E7%94%A8%E5%88%B0-spring-%E7%9A%84-transaction,需要翻墙可以访问

阅读全文
1 0