Building Routes Programmatically

If you prefer to not use annotations and declare all of your routes in code then never fear, Micronaut has a flexible RouteBuilder API that makes it a breeze to define routes programmatically.

To start off with you should subclass DefaultRouteBuilder and then simply inject the controller you wish to route to into the method and define your routes:

URI Variables Example

  1. import io.micronaut.context.ExecutionHandleLocator;
  2. import io.micronaut.web.router.DefaultRouteBuilder;
  3. import javax.inject.Inject;
  4. import javax.inject.Singleton;
  5. @Singleton
  6. public class MyRoutes extends DefaultRouteBuilder { (1)
  7. public MyRoutes(ExecutionHandleLocator executionHandleLocator, UriNamingStrategy uriNamingStrategy) {
  8. super(executionHandleLocator, uriNamingStrategy);
  9. }
  10. @Inject
  11. void issuesRoutes(IssuesController issuesController) { (2)
  12. GET("/issues/show/{number}", issuesController, "issue", Integer.class); (3)
  13. }
  14. }

URI Variables Example

  1. import io.micronaut.web.router.GroovyRouteBuilder
  2. import javax.inject.Inject
  3. import javax.inject.Singleton
  4. @Singleton
  5. class MyRoutes extends GroovyRouteBuilder { (1)
  6. MyRoutes(ExecutionHandleLocator executionHandleLocator, UriNamingStrategy uriNamingStrategy, ConversionService<?> conversionService) {
  7. super(executionHandleLocator, uriNamingStrategy, conversionService)
  8. }
  9. @Inject
  10. void issuesRoutes(IssuesController issuesController) { (2)
  11. GET("/issues/show/{number}", issuesController.&issue) (3)
  12. }
  13. }

URI Variables Example

  1. import io.micronaut.context.ExecutionHandleLocator
  2. import io.micronaut.web.router.DefaultRouteBuilder
  3. import io.micronaut.web.router.RouteBuilder
  4. import javax.inject.Inject
  5. import javax.inject.Singleton
  6. @Singleton
  7. class MyRoutes(executionHandleLocator: ExecutionHandleLocator, uriNamingStrategy: RouteBuilder.UriNamingStrategy) :
  8. DefaultRouteBuilder(executionHandleLocator, uriNamingStrategy) { (1)
  9. @Inject
  10. fun issuesRoutes(issuesController: IssuesController) { (2)
  11. GET("/issues/show/{number}", issuesController, "issue", Int::class.java) (3)
  12. }
  13. }
1Route definitions should subclass DefaultRouteBuilder
2Use @Inject to inject a method with the controller you want to route to
3Use methods such as GET to route to controller methods. Note that even though the issues controller is being used, the route has no knowledge of its @Controller annotation and thus the full path must be specified.
Unfortunately due to type erasure a Java method lambda reference cannot be used with the API. For Groovy there is a GroovyRouteBuilder class which can be subclassed that allows passing Groovy method references.