在使用Shiro前提下,开始是想在controller使用SecurityUtils.getSubject().getPrincipal()中获取当前用户信息,但结果报红了

org.springframework.beans.factory.BeanCreationException: Error
creating bean with name ‘studentController’ defined in file
[H:\lxt\target\classes\com\dang\controller\StudentController.class]:
Instantiation of bean failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [com.dang.controller.StudentController]: Constructor
threw exception; nested exception is
org.apache.shiro.UnavailableSecurityManagerException: No
SecurityManager accessible to the calling code, either bound to the
org.apache.shiro.util.ThreadContext or as a vm static singleton. This
is an invalid application configuration.

然后就开始排查呗
能出现这个错误的情况有一下几种

  • 没有在相关shiro类中使用注解@Bean

是spring 的环境中没有把shiro 某些需要的类表示为Bean ,导致Spring无法管理到自然获取不到,这个错误通常在ShiroConfig.java里面。
在这里插入图片描述

  • 自定义Filter要在shiroFilter后面

在这里插入图片描述
但是这些都没有问题,于是就推测是SecurityUtils.getSubject().getPrincipal()使用的场景不对,一开始为了方便直接在类里面定义了一个属性,初始化时就直接使用User user = (User) SecurityUtils.getSubject().getPrincipal();,此时获取不到当前用户信息。
SecurityUtils.getSubject().getPrincipal()只有在方法内,即处理转发用户请求时才会有Shiro.session的作用域,不在方法内获取的Shiro.session并不知道你是哪个用户,方法外并没有他的作用域,也就没有session了。
既然是这样,那就在方法中再定义,结果没有报错,测试也通过了。

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐