如何为 micronaut 中的所有控制器设置 base url?通过 application.yml 或任何配置

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

如何为所有控制器设置基础 url

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

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

   }
}

不是在每个控制器上写 /api 有一种方法可以在所有其余控制器端点的配置中将其写为基础 url

目前没有现成的此类功能 必须在 application.yml 中指定自定义属性并从控制器中引用它们

例如:

@Controller(“${my.config:/api}/foo”))

可以配置一次RouteBuilder.UriNamingStrategy (default implementation HyphenatedUriNamingStrategy)

  1. 添加一些自定义 属性 micronaut。context-path, application.yml:
micronaut:
  context-path: /someApiPath
  1. 创建 ConfigurableUriNamingStrategy 并展开 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)
    }
}

此配置将应用于所有控制器, 因为您的 HelloController URI 路径将是 /someApiPath/greet,如果缺少 属性 micronaut.context-path 那么 /greet:

@Controller
class HelloController {

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

   }
}