2013-08-27 164 views
5

我正在使用Spring Security进行方法权限检查。我想调用一个私有方法来收集一些数据发送到hasPermission()方法。以下是我尝试执行的操作,并且我得到SpelEvaluationException,因为Spring正在寻找MethodSecurityExpressionRoot中的localPrivateMethod。有没有办法做到这一点?谢谢。在Spring中调用私有方法@PreAuthorize

@PreAuthorize("hasPermission(new Object[]{#arg3, #localPrivateMethod(#arg1,#arg2)}, 'canDoThis')") 
    public long publicMethod1(long arg1, long arg2, long arg3) 
    { 
    } 

    private String localPrivateMethod(long a1, long a2) 
    { 
    } 
+0

这里的总体思路:http://stackoverflow.com/questions/13564627/spring-aop-not方法调用在另一个方法内 –

回答

18

您将无法调用私有方法,但可以在另一个spring bean中调用方法。在我的应用程序中,我有一个名为permissionEvaluator的@Component。然后,我引用它在@PreAuthorize像这样:

@PreAuthorize("@permissionEvaluator.canViewImageSet(#imageSet, principal)") 
@RequestMapping(value="/image", method=RequestMethod.GET) 
public String getImage(
     @RequestParam(value="imageSet", required=false) ImageSet imageSet) { 
    // method body 
} 

PermissionEvaluatorImpl看起来是这样的:

@Component(value="permissionEvaluator") 
public class PermissionEvaluatorImpl implements PermissionEvaluator 
{ 
    public PermissionEvaluatorImpl() {} 

    /** 
    * Determine if a user can view a given image. 
    */ 
    public boolean canViewImageSet(ImageSet imageSet, UserDetailsAdapter user) 
    { 
     // code to see if they should view this image 
    } 
} 

和PermissionEvaluator是我自己的接口,没有什么特别的,只是无论我需要评估的方法。

+0

我花了整整一个小时来研究类似的问题,当我看到你的答案时,我记得春天在其他类的代理上应用拦截器时,在同一类代理中调用方法时,吨应用http://stackoverflow.com/questions/13564627/spring-aop-not-working-for-method-call-inside-another-method –

+0

你需要做其他事情吗?我尝试了这一点,它不会工作。 – Tim

+0

如果你的permissionEvaluator是一个bean,那么你应该没问题。如果您手动设置您的bean而不是使用组件扫描,那么您将必须确保permissionEvaluator bean存在。 – digitaljoel

0

私有方法不能被调用,但是你可以通过this.参考“这个组件”:

@PreAuthorize("hasPermission(new Object[]{#arg3, /* HERE: */ this.localPublicMethod(#arg1,#arg2)}, 'canDoThis')") 
public long publicMethod1(long arg1, long arg2, long arg3) 
{ 
} 

public String localPublicMethod(long a1, long a2) 
{ 
} 
相关问题