Spring中如何合并多注解为一个?实现自定义@GetJson注解方法
实现自定义@GetJson注解的方案
在Spring框架中,你可以通过元注解组合的方式,将@GetMapping和@ResponseBody合并为自定义的@GetJson注解,具体实现步骤如下:
1. 定义@GetJson注解
创建Kotlin注解类,通过元注解复用Spring原生注解的功能,并通过@AliasFor实现路径参数的传递:
import org.springframework.core.annotation.AliasFor import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.ResponseBody import kotlin.annotation.AnnotationTarget.FUNCTION import kotlin.annotation.AnnotationRetention.RUNTIME @Target(FUNCTION) @Retention(RUNTIME) @GetMapping @ResponseBody annotation class GetJson( @AliasFor(annotation = GetMapping::class) val value: Array<String> = [] )
2. 关键细节说明
- 元注解组合:直接将
@GetMapping和@ResponseBody标注在自定义注解上,Spring会自动将这两个注解的行为合并到@GetJson中 - 参数映射:通过
@AliasFor将自定义注解的value属性与@GetMapping的value属性关联,你在@GetJson中指定的路径会被Spring识别为请求映射路径 - 注解作用范围:
@Target(FUNCTION)限定注解只能用在方法上,@Retention(RUNTIME)保证Spring在运行时能读取到这个注解的信息
3. 使用示例
按照你的需求,改造后的代码直接使用@GetJson即可:
@GetJson("/test-get") fun testGet(): String { return "test get" }
这个自定义注解完全等价于同时使用@GetMapping和@ResponseBody的效果,请求/test-get时会直接返回字符串test get作为JSON响应。
内容的提问来源于stack exchange,提问作者chikadance
相关产品推荐
相关产品推荐

