我正在尝试使用方法安全性,所以我使用了 dispatcher-servlet.xml(security.xml 在另一个上下文中):
<security:global-method-security secured-annotations="enabled" jsr250-annotations="enabled" />
并将@RolesAllowed 放在 Controller 上:
@SessionAttributes({"sessionCompanyDetails"})
@Controller
@RequestMapping("/company")
@RolesAllowed("ROLE_ADMIN")
public class CompanyController extends BaseController {
...
我意识到,当我使用这些注解时,Spring 为 Controller 创建了一个代理,因此我得到了错误:
java.lang.IllegalArgumentException:object is not an instance of declaring class
最佳答案
问题的发生是因为Controller没有接口(interface),所以Spring创建了一个代理但是不能转换到Controller类。
可能的解决方案是:
- 拦截器:使用 MethodSecurityInterceptor 和 AccessDecisionManager
- 使用
<global-method-security proxy-target-class="true"/>
激活 CGLib 代理(代理类是子类),因此 Spring 可以转换它。 - 创建 Controller 接口(interface)。
- 使用 ApectJ。
我测试了除 ApectJ 之外的所有解决方案。我在一个项目中使用 CGLib 解决方案,在另一个项目中使用拦截器,这两种解决方案都可以正常工作。
关于java - 在 Controller 上使用@RolesAllowed 并获取 "object is not an instance of declaring class",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9182903/