kotlinjvmmicronaut

How to set base url for all controllers in micronaut ? through application.yml or any configuration


How to set base url for all controllers

 @Controller("/api/hello")
class HelloController{

    @Get("/greet")
   fun greet(){

   }
}

Instead of writing /api on each controller is there a way to write it as base url in configuration for all rest controller endpoints


Solution

  • You can configure once RouteBuilder.UriNamingStrategy (default implementation HyphenatedUriNamingStrategy)

    1. add some custom property micronaut.context-path, application.yml:
    micronaut:
      context-path: /someApiPath
    
    1. create ConfigurableUriNamingStrategy and extend HyphenatedUriNamingStrategy :
    @Singleton
    @Replaces(HyphenatedUriNamingStrategy::class)
    class ConfigurableUriNamingStrategy : HyphenatedUriNamingStrategy() {
        
        @Value("\${micronaut.context-path}")
        var contextPath: String? = null
    
        override fun resolveUri(type: Class<*>?): String {
            return contextPath ?: "" + super.resolveUri(type)
        }
    
        override fun resolveUri(beanDefinition: BeanDefinition<*>?): String {
            return contextPath ?: "" + super.resolveUri(beanDefinition)
        }
    
        override fun resolveUri(property: String?): String {
            return contextPath ?: "" + super.resolveUri(property)
        }
    
        override fun resolveUri(type: Class<*>?, id: PropertyConvention?): String {
            return contextPath ?: "" + super.resolveUri(type, id)
        }
    }
    

    This configurations will be applied for all controllers, for your HelloController URI path will be /someApiPath/greet, if the property micronaut.context-path is missing then /greet:

    @Controller
    class HelloController {
    
       @Get("/greet")
       fun greet(){
    
       }
    }