如何为Micronaut中的所有控制器设置基本URL?通过application.yml或任何配置



如何为所有控制器设置基本URL

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

而不是在每个控制器上写下/API,因此可以将其写入所有REST Controller端点的配置中的基本URL

您可以在RouteBuilder.URINAMINGSTRATEGY(默认实现杂种inurinamingStrategy(

配置一旦配置
  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(){
   }
}

目前没有此类功能必须在application.ym中指定自定义属性,并从控制器中转介

eg:

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

最新更新