You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Controller(Kotlin)中如何实现三级URL映射?

Spring多级层次化URL映射实现方案

Spring不支持通过嵌套内部类的方式实现中间级URL映射,因为Spring组件扫描仅识别顶级的@Controller/@RestController类,内部类即便添加了@RequestMapping注解,也不会被自动注册为Spring MVC的控制器Bean,所以你写的嵌套内部类代码不会生效。

针对你的需求,有两种更合理的实现方式:

方式一:拆分Controller类

将需要共享中间级URL前缀的4个方法单独抽离到一个新的控制器类,统一配置前缀,剩下的2个方法保留在原控制器中:

@RestController
@RequestMapping("level1/level2")
class GroupedController {
    @GetMapping("level3")
    fun method1() {}

    @PostMapping("level4")
    fun method2() {}

    // 另外2个同前缀方法
}

@RestController
@RequestMapping("level1")
class MainController {
    // 剩下2个非分组方法
    @GetMapping("other-path")
    fun otherMethod() {}
}

方式二:同一类内复用路径前缀

如果不想拆分类,可以通过定义常量或直接拼接路径的方式,复用中间级前缀:

@RestController
@RequestMapping("level1")
class MainController {
    // 定义共享的中间级路径前缀
    private const val GROUP_PREFIX = "level2"

    // 分组的4个方法
    @GetMapping("$GROUP_PREFIX/level3")
    fun method1() {}

    @PutMapping("$GROUP_PREFIX/level4")
    fun method2() {}

    // 剩下2个非分组方法
    @GetMapping("direct-path")
    fun otherMethod() {}
}

补充说明

如果你的中间级前缀非常复杂,还可以通过自定义注解来复用路径配置,比如:

@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
@RequestMapping("level1/level2")
annotation class GroupMapping

// 使用自定义注解
@RestController
class MainController {
    @GroupMapping
    @GetMapping("level3")
    fun method1() {}
}

内容的提问来源于stack exchange,提问作者오준후

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 11:17:34