Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 用于授权的自定义批注_Java_Spring_Annotations_Spring Annotations - Fatal编程技术网

Java 用于授权的自定义批注

Java 用于授权的自定义批注,java,spring,annotations,spring-annotations,Java,Spring,Annotations,Spring Annotations,我希望创建一个自定义注释,用于检查用户是否有权对某个产品ID进行操作。该注释将放置在我的控制器中的方法上,该控制器在Spring管理的应用程序中运行 @ProductDemand(id = {productId}) @RequestMapping(value = "/product/{productID}", method = RequestMethod.PUT) public Product update(Product toUpdate) { User user = getUserF

我希望创建一个自定义注释,用于检查用户是否有权对某个产品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

我以前从未写过任何自定义注释,因此如果这没有意义,请让我知道

谢谢,
Phil

使用spring特性,您可以将切入点与自定义注释一起使用。 然后,你可以在之前、之后、周围等处应用建议。这就是你想要的


下面是一个示例

您看过Spring Security吗?它提供了一个框架来实现您正在尝试做的事情。请检查我的答案,但老实说,我不记得三年后的细节:-)在这个答案中,我计算了布尔变量btw