如何用spring做自定义请求映射注解添加前缀?

问题描述 投票:0回答:1

在 java 11 上使用 spring boot 2,我想为每个 REST API 版本(例如:“/api/v1/”)做一个自定义注释,可以与后续 URI 组件连接,如下所示:

@APIv1("/users/")    // this annotation should prepend "/api/v1/{argument}"
public class UserController {
    @GetMapping("/info")
    public String info() {return "This should be returned at /api/v1/users/info/";}

    /* More methods with mappings */
}

问题是我不知道如何定义 @APIv1 注释。 根据我的搜索,我参考了 https://stackoverflow.com/a/51182494/ 来编写以下内容:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RestController
@RequestMapping("/api/v1")
@interface APIv1 {
    @AliasFor(annotation = RestController.class)
    String value() default "";
}

但这不能处理参数。无论参数是否给出,与上面相同的操作都会路由到 /api/v1/info/。这总比没有好,因为我可以将方法注释切换为 @GetMapping("/users/info"),但我想知道是否有一种方法可以将常量与参数结合起来,以减少同一控制器类中方法注释之间的重复。

java spring spring-boot spring-annotations
1个回答
0
投票

@APIv1 你定义:

@RequestMapping("/api/v1")

所以它按照你说的那样工作。

© www.soinside.com 2019 - 2024. All rights reserved.