Programmatic Routes with GroovyRouterBuilder
If you prefer to build your routes programmatically (similar to Grails UrlMappings
), a special io.micronaut.web.router.GroovyRouteBuilder
exists that has some enhancements to make the DSL better.
The following example shows GroovyRouteBuilder
in action:
Using GroovyRouteBuilder
@Singleton
static class MyRoutes extends GroovyRouteBuilder {
MyRoutes(ApplicationContext beanContext) {
super(beanContext)
}
@Inject
void bookResources(BookController bookController, AuthorController authorController) {
GET(bookController) {
POST("/hello{/message}", bookController.&hello) (1)
}
GET(bookController, ID) { (2)
GET(authorController)
}
}
}
1 | You can use injected controllers to create routes by convention and Groovy method references to create routes to methods |
2 | The ID property can be used to reference include an {id} URI variable |
The above example results in the following routes:
/book
- Maps toBookController.index()
/book/hello/{message}
- Maps toBookController.hello(String)
/book/{id}
- Maps toBookController.show(String id)
/book/{id}/author
- Maps toAuthorController.index