如何在Javalin中于多路径层级复用同一组路由实现DRY重构?
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
RouteGroupis 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
doThingAordoThingB(like modifying the handler or HTTP method) only need to be made once in thesharedRoutesfunction, 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
相关产品推荐
相关产品推荐

