刚开始spring boot 整合shiro缓存使用的是ehcache,自动注入userService如下,没有问题
@Autowired
@Lazy
private SysUserService userService;
当将缓存换成了redis后,该注解无效,一直空指针,大概是因为 Spring 加载顺序等原因
解决方案是在自定义Realm中不直接使用@Autowired,而是将userService定义成成员变量,再
private SysUserService userService;
@Autowired
private void setSysUserService(SysUserService userService) {
this.userService = userService;
}
另外一个点就是SecurityManager的setRealm方法,不能直接new 自定义Realm,而是要以参数的形式传入
@Bean
public SecurityManager securityManager(@Qualifier("myShiroRealm")MyShiroRealm myShiroRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 设置realm.
securityManager.setRealm(myShiroRealm);
securityManager.setCacheManager(cacheManager());
securityManager.setSessionManager(sessionManager());
return securityManager;
}
附完整ShiroConfig
package cn.com.suntree.cmp.config;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.subject.PrincipalCollection;