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

如何在Javalin中于多路径层级复用同一组路由实现DRY重构?

Reuse Shared Routes in Javalin (DRY Principle)

To eliminate redundant route definitions in your Javalin setup, you can define your shared routes as an extension function on RouteGroup. This lets you reuse the same set of routes across multiple path levels with a single function call.

Step 1: Define Shared Routes as an Extension Function

Create an extension function that encapsulates your common routes, adding them to any RouteGroup context:

import io.javalin.router.RouteGroup

// Replace YourController with your actual controller type
fun RouteGroup.sharedRoutes(controller: YourController) {
    path("doThingA") {
        post(controller::doThingA)
    }
    path("doThingB") {
        post(controller::doThingB)
    }
}

Step 2: Use the Shared Routes in Your Path Hierarchy

Call sharedRoutes(controller) inside any path block where you want to inject the common routes. This replaces all duplicated code:

app.routes {
    path("api/") {
        path("company/{companyId}") {
            sharedRoutes(controller) // Add routes at company level
            path("application/{applicationId}") {
                sharedRoutes(controller) // Add routes at application level
                path("project/{environmentId}") {
                    sharedRoutes(controller) // Add routes at project level
                }
            }
        }
    }
}

Why This Works

  • RouteGroup is Javalin's core context for defining routes. The extension function operates directly on this context, adding your shared routes to the current path hierarchy wherever it's called.
  • Any updates to doThingA or doThingB (like modifying the handler or HTTP method) only need to be made once in the sharedRoutes function, ensuring consistency across all path levels.

Alternative: Regular Function (If Extension Functions Aren't Preferred)

If you prefer not to use extension functions, define a regular function that accepts a RouteGroup parameter:

fun addSharedRoutes(group: RouteGroup, controller: YourController) {
    group.path("doThingA") {
        post(controller::doThingA)
    }
    group.path("doThingB") {
        post(controller::doThingB)
    }
}

// Usage
app.routes {
    path("api/") {
        path("company/{companyId}") {
            addSharedRoutes(this, controller)
            // ... rest of the hierarchy
        }
    }
}

内容的提问来源于stack exchange,提问作者chrisaitk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 09:20:29