如何为自定义@RequestMapping注解的参数值自动添加固定路径前缀
自定义@StudentApiController注解路径前缀问题解决方案
错误原因
你当前写法触发报错的根本原因是:Java/Kotlin 中注解参数的默认值必须是编译期可确定的常量,你使用 "/student" + value 作为默认值时,value 是调用注解时传入的动态参数,编译阶段无法确定具体值,因此不符合语法规则。
实现方案
我们通过全局路径前缀匹配规则实现自动加前缀的需求,不需要在注解定义阶段做字符串拼接,具体步骤如下:
1. 调整自定义注解定义
直接把 value 字段和 @RequestMapping 的 value 属性做别名映射即可:
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @RequestMapping annotation class StudentApiController( @get:AliasFor(annotation = RequestMapping::class, attribute = "value") val value: String = "" )
2. 配置全局路径前缀规则
实现 WebMvcConfigurer 接口,给所有标注了 @StudentApiController 的控制器统一添加 /student 前缀:
@Configuration class WebConfig : WebMvcConfigurer { override fun configurePathMatch(configurer: PathMatchConfigurer) { // 给标注了@StudentApiController的类统一加/student前缀 configurer.addPathPrefix("/student") { clazz -> clazz.isAnnotationPresent(StudentApiController::class.java) } } }
效果验证
你给出的两种示例用法都可以正常生效:
@StudentApiController("/payment")最终映射路径为/student/payment@StudentApiController("/exam")最终映射路径为/student/exam
可选优化
如果你的控制器都是返回JSON的接口,可以直接在自定义注解上组合@RestController,减少重复的注解声明:
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @RestController // 组合RestController能力 @RequestMapping annotation class StudentApiController( @get:AliasFor(annotation = RequestMapping::class, attribute = "value") val value: String = "" )
调整后标注了@StudentApiController的类不需要额外加@RestController也能被Spring识别为接口控制器。
内容的提问来源于stack exchange,提问作者user3773215
相关产品推荐
相关产品推荐

