Spring声明式REST Client如何自动转换URL中的自定义类型?
解决Spring声明式REST Client中自定义值类型的路径变量转换问题
方案1:实现Spring Converter并全局注册
Spring的类型转换系统支持自定义转换器,你可以实现一个将CustomId转换为String的转换器,让Spring在处理路径变量时自动使用它,替代默认的toString()调用。
- 编写Converter实现类:
import org.springframework.core.convert.converter.Converter class CustomIdToStringConverter : Converter<CustomId, String> { override fun convert(source: CustomId): String { return source.id // 直接返回内部封装的id字符串 } }
- 将Converter注册到Spring上下文:
通过配置类全局注册,让所有Spring组件都能使用这个转换规则:
import org.springframework.context.annotation.Configuration import org.springframework.format.FormatterRegistry import org.springframework.web.servlet.config.annotation.WebMvcConfigurer @Configuration class WebConfig : WebMvcConfigurer { override fun addFormatters(registry: FormatterRegistry) { registry.addConverter(CustomIdToStringConverter()) } }
如果需要仅针对RestClient实例生效,可以在构建RestClient时指定自定义转换服务:
import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.core.convert.support.DefaultConversionService import org.springframework.web.client.RestClient @Configuration class RestClientConfig { @Bean fun fooClient(): FooClient { val conversionService = DefaultConversionService() conversionService.addConverter(CustomIdToStringConverter()) return RestClient.builder() .baseUrl("http://your-service-base-url") .messageConverters { converters -> converters.forEach { converter -> if (converter is org.springframework.http.converter.GenericHttpMessageConverter<*>) { converter.setConversionService(conversionService) } } } .build() .create(FooClient::class.java) } }
方案2:使用SpEL表达式(临时应急方案)
如果不想编写全局转换器,也可以在@GetExchange的路径中直接通过SpEL表达式提取CustomId内部的id属性:
interface FooClient { @GetExchange(value = "/service/#{id.id}") fun hamtaTaxeringsenhet(id: CustomId): Bar }
注意这个方案需要在每个使用CustomId的接口方法中单独配置,复用性较差,适合临时场景。
关键说明
- 方案1的转换器是全局生效的,所有需要将
CustomId转换为String的场景(包括路径变量、请求参数等)都会自动应用该规则,适合长期复用。 - 由于
CustomId是@JvmInline修饰的值类,Spring可以正常识别其内部的id属性,无需额外配置。
内容的提问来源于stack exchange,提问作者Peter Westlin
相关产品推荐
相关产品推荐

