关于shiro权限控制 cannot be cast to

时间:2025-04-20 12:19:04

20:49:48,266 ERROR DefaultDispatcherErrorHandler:42 - Exception occurred during processing request: Unable to instantiate Action, userAction,  defined for 'userAction_logout' in namespace '/'Error creating bean with name 'userAction' defined in file [C:\Java_Tools\apache-tomcat-7.0.69\webapps\bose\WEB-INF\classes\com\yepp\boss\web\action\]: Instantiation of bean failed; nested exception is : Failed to instantiate []: Constructor threw exception; nested exception is : cannot be cast to

Unable to instantiate Action, userAction,  defined for 'userAction_logout' in namespace '/'Error creating bean with name 'userAction' defined in file [C:\Java_Tools\apache-tomcat-7.0.69\webapps\bose\WEB-INF\classes\com\yepp\boss\web\action\]: Instantiation of bean failed; nested exception is : Failed to instantiate []: Constructor threw exception; nested exception is : cannot be cast to - action - file:/C:/Java_Tools/apache-tomcat-7.0.69/webapps/bose/WEB-INF/classes/:44:63
at .(:314)
at .(:395)
at .(:194)
at .(:63)
at .(:37)
at .(:58)
at .(:554)
at .(:81)
at .(:99)
at (:241)
at (:208)
at .(:151)
at (:107)
at (:241)
at (:208)
at (:61)
at (:108)
at (:137)
at (:125)
at (:66)
at (:449)
at $(:365)
at (:90)
at (:83)
at (:383)
at (:362)
at (:125)
at (:346)
at (:262)
at (:241)
at (:208)
at (:220)
at (:122)
at (:505)
at (:169)
at (:103)
at (:956)
at (:116)
at (:436)
at .http11.(:1078)
at $(:625)
at $(:318)
at (:1142)
at $(:617)
at $(:61)
at (:745)
Caused by: : Error creating bean with name 'userAction' defined in file [C:\Java_Tools\apache-tomcat-7.0.69\webapps\bose\WEB-INF\classes\com\yepp\boss\web\action\]: Instantiation of bean failed; nested exception is : Failed to instantiate []: Constructor threw exception; nested exception is : cannot be cast to
at (:1105)
at (:1050)
at (:510)
at (:482)
at (:325)
at (:197)
at (:1054)
at .(:161)
at .(:178)
at .(:22)
at .(:148)
at .(:295)
... 45 more
Caused by: : Failed to instantiate []: Constructor threw exception; nested exception is : cannot be cast to
at (:163)
at (:89)
at (:1098)
... 56 more
Caused by: :
cannot be cast to
at .<init>(:75)
at .<init>(:23)
at .newInstance0(Native Method)
at (:62)
at (:45)
at (:423)
at (:147)

... 58 more


分析因为shiro的自动代理使用的cglib动态代理,代理过程中会在内存中拼接产生当前调用对象()的子类代理对象而此时baseAction构造中代码:

ParameterizedTypegenericSuperclass = (ParameterizedType)().getSuperclass().getGenericSuperclass();

这个强转会有风险,因为遇到注解上的权限时,会用到cglib动态代理,

此时的().getSuperclass()得到的是当前实际的Action,并不是BaseAction,所以就得不到BaseAction的泛型类型;

解决办法:把构造中的那个强转加个判断:

 //得到父类(BaseDao<T>)的类型

        ParameterizedType genericSuperclass =null;

        Type genericSuperclass2 =().getGenericSuperclass();

        if(genericSuperclass2 instanceofParameterizedType){

               genericSuperclass =(ParameterizedType) genericSuperclass2;

        }else{

               genericSuperclass =(ParameterizedType) ().getSuperclass().getGenericSuperclass();

        }