我对AOP还是个新手,对我所面临的问题感到困惑。我有注解@AuthorizeUser,它作用于表示层上的方法。我需要检查用户是否被授权执行该方法。以下是AuthorizeUserAspect的代码:
@Aspect
public class AuthorizeUserAspect {
@AuthoWired
private UserService service;
@Before(value = "@annotation(com.company.annotation.AuthorizeUser)")
public void isAuthorized(JoinPoint jp) {
// Check if the user has permission or not
// executing some Service Layer services and
// Persistence Layer, corresponding to that
service.checkUser();
// Is there a way I can make this method Conditional. something like:
if ( /* User has permission */ ) {
// do nothing, so the method will be executed after this
}
else {
// 1) Prevent the Method to be executed [and/or]
// 2) Pass some Parameters to the method for checking [and/or]
// 3) Execute another method on that class [e.g showAccessDenied()]
}
}
}它有点类似于这个问题Spring MVC + Before Advice check security。但它建议返回一些字符串(即."Not OK")。我的应用程序中有两种类型的UI (Struts和Jersey),因此会有两种类型的返回类型(分别为String和Response )。所以我猜这可能不是最好的方法。
如果您能向我展示解决此问题的方法,我将非常高兴。
这到底是不是一个好方法呢?
发布于 2012-09-03 22:13:24
首先,你看过Spring Security吗?它完全是声明性的,不需要你自己编写方面。如果用户未通过身份验证或没有所需的权限,它将通过抛出异常来保护方法。
关于两种不同返回类型的问题:
第一个选项:创建两种不同的建议,具体针对方法的返回类型:
@Before("@annotation(com.company.annotation.AuthorizeUser) && execution(String *.*(..))")
public void isAuthorizedString(JoinPoint jp) {
...
}
@Before("@annotation(com.company.annotation.AuthorizeUser) && execution(Response *.*(..))")
public void isAuthorizedResponse(JoinPoint jp) {
...
}第二种选择:通过反射找出被建议方法的返回类型,并在此基础上返回一个不同的值:
@Before("@annotation(com.company.annotation.AuthorizeUser")
public void isAuthorized(JoinPoint jp) {
Class<?> returnType = ((MethodSignature)jp.getStaticPart()
.getSignature()).getReturnType();
if(returnType == String.class)
...
else
...
}https://stackoverflow.com/questions/12248716
复制相似问题