首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring-AOP在通知之前的条件行为

Spring-AOP在通知之前的条件行为
EN

Stack Overflow用户
提问于 2012-09-03 21:20:01
回答 1查看 2.7K关注 0票数 1

我对AOP还是个新手,对我所面临的问题感到困惑。我有注解@AuthorizeUser,它作用于表示层上的方法。我需要检查用户是否被授权执行该方法。以下是AuthorizeUserAspect的代码:

代码语言:javascript
复制
@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),因此会有两种类型的返回类型(分别为StringResponse )。所以我猜这可能不是最好的方法。

如果您能向我展示解决此问题的方法,我将非常高兴。

这到底是不是一个好方法呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-09-03 22:13:24

首先,你看过Spring Security吗?它完全是声明性的,不需要你自己编写方面。如果用户未通过身份验证或没有所需的权限,它将通过抛出异常来保护方法。

关于两种不同返回类型的问题:

第一个选项:创建两种不同的建议,具体针对方法的返回类型:

代码语言:javascript
复制
@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) {
    ...
}

第二种选择:通过反射找出被建议方法的返回类型,并在此基础上返回一个不同的值:

代码语言:javascript
复制
@Before("@annotation(com.company.annotation.AuthorizeUser")
public void isAuthorized(JoinPoint jp) {
    Class<?> returnType = ((MethodSignature)jp.getStaticPart()
            .getSignature()).getReturnType();
    if(returnType == String.class)
        ...
    else
        ...
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12248716

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档