授权的自定义注释

时间:2015-10-29 16:55:30

标签: java spring annotations spring-annotations

我希望创建一个自定义注释,用于检查用户是否有权对某个产品ID进行操作。注释将放在我的控制器中的方法中,该方法在Spring托管应用程序中运行。

@ProductDemand(id = {productId})
@RequestMapping(value = "/product/{productID}", method = RequestMethod.PUT)
public Product update(Product toUpdate) {
    User user = getUserFromHeaderValues();
}

在这种情况下,@ ProductDemand是我需要创建的自定义注释。如果用户无权对具有给定ID的产品采取行动,我想返回403.

到目前为止我的注释是:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ProductDemand {
    String productId;
}

我还有一项服务来授权这些价值观:

public class AuthorizationService {
    public boolean authorize(UUID userUUID, String productID) {
        //do auth
    }
}

我想要做的是能够将该注释放在任何方法上,并让它自动调用AuthorizationService中的authorize方法。显然,两者之间会有一些管道来获取价值并挂钩授权服务,但我目前不知道如何做到这一点。最好是,我希望能够将所有这些包装起来,并允许某人能够将其导入到他们的项目中,并且只需添加注释就可以使用它,如果需要也可以使用bean。

我之前从未写过任何自定义注释,如果这没有意义,请告诉我。

谢谢, 菲尔

1 个答案:

答案 0 :(得分:1)

使用弹簧方面,您可以在自定义注释中使用切入点。 然后你可以在之前,之后,周围等地提出建议。这就是你想要的

以下是示例@AspectJ pointcut for all methods of a class with specific annotation