Programmatic Routes with GroovyRouterBuilder

If you prefer to build your routes programmatically (similar to Grails UrlMappings) then a special io.micronaut.web.router.GroovyRouteBuilder exists that has some enhancements to make the DSL better.

The following example shows GroovyRouteBuilder in act:

Using GroovyRouteBuilder

  1. @Singleton
  2. static class MyRoutes extends GroovyRouteBuilder {
  3. MyRoutes(ApplicationContext beanContext) {
  4. super(beanContext)
  5. }
  6. @Inject
  7. void bookResources(BookController bookController, AuthorController authorController) {
  8. GET(bookController) {
  9. POST("/hello{/message}", bookController.&hello) (1)
  10. }
  11. GET(bookController, ID) { (2)
  12. GET(authorController)
  13. }
  14. }
  15. }
1You can use injected controllers to create routes by convention and Groovy method references to create routes to methods
2The ID property can be used to reference include an {id} URI variable

The above example results in the following routes:

  • /book - Maps to BookController.index()

  • /book/hello/{message} - Maps to BookController.hello(String)

  • /book/{id} - Maps to BookController.show(String id)

  • /book/{id}/author - Maps to AuthorController.index