【问题标题】:Custom anotaion for ApiController to prefix /api not working Spring BootApiController 的自定义 anotaion 前缀 /api 不起作用 Spring Boot
【发布时间】:2020-07-09 04:35:51
【问题描述】:

我已经定义了一个 ApiController 来添加前缀 (/api) 来匹配路由。我正在使用 Spring Boot

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@RestController
@RequestMapping("/api")
public @interface ApiController {

    @AliasFor(annotation = RequestMapping.class, attribute = "value")
    String[] value();

}

并在控制器中使用,如

@ApiController("/user")
public class UserController {

    /**
     * Define url methods
     *
     */
}

但我不知道为什么 /api/user/ 不提供服务。它服务于 /user/ 端点。有谁知道具体的错误吗?

【问题讨论】:

    标签: java spring-boot spring-mvc


    【解决方案1】:

    我在下面解释,检查@RestController的实现后如何解决问题。

    我为 RestController 创建了一个别名

    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @RestController
    public @interface ApiController {
    
        @AliasFor(
                annotation = RestController.class
        )
        String value() default "";
    }
    

    然后我创建一个配置来添加前缀。

    @Configuration
    public class Config implements WebMvcConfigurer {
    
        @Override
        public void configurePathMatch(PathMatchConfigurer configurer) {
            configurer.addPathPrefix("/api", HandlerTypePredicate.forAnnotation(ApiController.class));
        }
    }
    

    它对我有用。

    【讨论】:

      【解决方案2】:

      当你使用@AliasFor时,这意味着你的注解的属性是另一个注解的属性的别名。在您的示例中,ApiController.valueRequestMapping.value 的别名,当您设置ApiController.value 时,相同的值设置为RequestMapping.value。不添加或连接,只需设置新值。您可以阅读@AliasFor 的工作原理here

      你的问题呢。据我了解,您想设置 api root url。您可以使用this question 中的一种方式来完成。请注意,在选项 2 中,使用了相同的技术,但没有使用 @AliasFor 覆盖/扩展 RequestMapping.value

      【讨论】:

      • 实际上我已经尝试了很多,包括您建议中的选项 2,但没有任何成果。不过,感谢您的帮助。
      • 这很奇怪。你能不能在 选项 2 中什么不起作用?
      猜你喜欢
      • 1970-01-01
      • 2021-08-28
      • 2019-12-27
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      • 2023-01-31
      • 1970-01-01
      • 2023-02-14
      相关资源
      最近更新 更多