Spring Boot整合shiro后导致@Transactional等注解失效的问题以及解决

Spring Boot整合shiro后导致@Transactional等注解失效的问题以及解决

部分转载自:https://blog.csdn.net/gnail_oug/article/details/80706205

一、问题描述

  • Springboot整合shiro前,service里的@Cacheable、@Transactional等注解都正常使用。
  • 整合shiro之后,UserRealm类里自动注入的service中的注解失效(初步判断Shiro的初始化bean会影响到Spring bean的初始化,导致某些bean的事务失效)

UserRealm代码如下:

public class UserRealm extends AuthorizingRealm {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserRealm.class);
    /**
     * 这种情况下SysUserService里缓存、事务等注解失效
     */
    @Autowired
    private SysUserService sysUserService;

    //省略其他代码
}

SysUserService代码如下:

@Service
public class SysUserService {
    @Autowired
    private SysUserMapper userMapper;

    @Cacheable(cacheNames = "users", key = "'sysuser:'+#userName")
    public SysUser findByUserName(String userName) {
        return userMapper.findByUserName(userName);
    }
}

解决方法一

在UserRealm自动注入service时,添加@Lazy注解延迟注入,如下:

public class UserRealm extends AuthorizingRealm {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserRealm.class);
    /**
     * 添加@Lazy注解延迟注入
     */
    @Autowired
    @Lazy
    private SysUserService sysUserService;

    /**
     * 添加@Lazy注解延迟注入
     */
    @Autowired
    @Lazy
    private SysPermissionService sysPermissionService;

    //省略其他代码
}

解决方法二

orm映射框架的Mapper类,不是由Spring生成初始化,只是交给Spring管理,不会影响Spring bean的初始化

public class UserRealm extends AuthorizingRealm {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserRealm.class);
    @Autowired
    private SysUserMapper sysUserMapper;
    
    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    //省略其他代码
}

你可能感兴趣的:(IT)