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
import io.micronaut.context.ExecutionHandleLocator;
import io.micronaut.web.router.DefaultRouteBuilder;
import javax.inject.Inject;
import javax.inject.Singleton;
@Singleton
public class MyRoutes extends DefaultRouteBuilder { (1)
public MyRoutes(ExecutionHandleLocator executionHandleLocator, UriNamingStrategy uriNamingStrategy) {
super(executionHandleLocator, uriNamingStrategy);
}
@Inject
void issuesRoutes(IssuesController issuesController) { (2)
GET("/issues/show/{number}", issuesController, "issue", Integer.class); (3)
}
}
URI Variables Example
import io.micronaut.web.router.GroovyRouteBuilder
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class MyRoutes extends GroovyRouteBuilder { (1)
MyRoutes(ExecutionHandleLocator executionHandleLocator, UriNamingStrategy uriNamingStrategy, ConversionService<?> conversionService) {
super(executionHandleLocator, uriNamingStrategy, conversionService)
}
@Inject
void issuesRoutes(IssuesController issuesController) { (2)
GET("/issues/show/{number}", issuesController.&issue) (3)
}
}
URI Variables Example
import io.micronaut.context.ExecutionHandleLocator
import io.micronaut.web.router.DefaultRouteBuilder
import io.micronaut.web.router.RouteBuilder
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class MyRoutes(executionHandleLocator: ExecutionHandleLocator, uriNamingStrategy: RouteBuilder.UriNamingStrategy) :
DefaultRouteBuilder(executionHandleLocator, uriNamingStrategy) { (1)
@Inject
fun issuesRoutes(issuesController: IssuesController) { (2)
GET("/issues/show/{number}", issuesController, "issue", Int::class.java) (3)
}
}
1 | Route definitions should subclass DefaultRouteBuilder |
2 | Use @Inject to inject a method with the controller you want to route to |
3 | Use 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. |