Spring 5.3 XML配置项目方法安全实现失败求助
问题根源
你在方案2中遇到的EL1057E: No bean resolver registered错误,本质是Spring Security的表达式处理器没有绑定Spring容器的Bean解析器,导致无法识别@mySecurity这种引用容器内Bean的EL语法。
具体配置实现
1. 注册Spring EL Bean解析器
先定义StandardBeanExpressionResolver,它负责从Spring容器中查找并解析Bean引用:
<bean id="beanExpressionResolver" class="org.springframework.context.expression.StandardBeanExpressionResolver"/>
2. 配置方法安全表达式处理器
定义DefaultMethodSecurityExpressionHandler,注入上面的Bean解析器,让它能处理@beanName格式的EL表达式:
<bean id="methodSecurityExpressionHandler" class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler"> <property name="beanResolver" ref="beanExpressionResolver"/> </bean>
3. 配置PrePost授权管理器
使用PrePostAuthorizationManager来处理@PreAuthorize注解,关联表达式处理器:
<bean id="prePostAuthorizationManager" class="org.springframework.security.authorization.method.PrePostAuthorizationManager"> <constructor-arg ref="methodSecurityExpressionHandler"/> </bean>
4. 配置拦截器并绑定到AOP
定义AuthorizationManagerBeforeMethodInterceptor,指定拦截规则,然后通过AOP advisor让拦截器生效:
<bean id="prePostInterceptor" class="org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor"> <constructor-arg ref="prePostAuthorizationManager"/> <!-- 可根据需求调整切点,这里示例拦截所有带@PreAuthorize的方法 --> <property name="pointcut" expression="@annotation(org.springframework.security.access.prepost.PreAuthorize)"/> </bean> <aop:config> <aop:advisor advice-ref="prePostInterceptor" pointcut="@annotation(org.springframework.security.access.prepost.PreAuthorize)"/> </aop:config>
5. 修正security.xml核心配置
确保sec:method-security开启pre-post支持,并关联表达式处理器和授权管理器:
<sec:method-security pre-post-enabled="true"> <sec:expression-handler ref="methodSecurityExpressionHandler"/> <sec:authorization-manager ref="prePostAuthorizationManager"/> </sec:method-security>
方案1异常补充排查
方案1启动报错combinedScriptResources,大概率是项目依赖中Spring Security与脚本类库(如Spring Scripts)版本冲突,或是配置了脚本相关Bean但参数类型不匹配。若要继续用方案1,建议排查依赖树,排除冲突的脚本依赖,或检查是否有其他脚本相关Bean的配置干扰了方法安全模块的初始化。
内容的提问来源于stack exchange,提问作者recalcitrant
相关产品推荐
相关产品推荐

