irc*_*cho 5 java spring spring-mvc spring-boot
我们基本上遇到了与这个问题相同的问题,但对于列表,此外,我们正在寻找一个全局解决方案。
目前我们有一个定义如下的 REST 调用:
@RequestMapping
@ResponseBody
public Object listProducts(@RequestParam(value = "attributes", required = false) List<String> attributes) {
Run Code Online (Sandbox Code Playgroud)
调用工作正常,当这样调用时,列表属性将包含两个元素“test1:12,3”和“test1:test2”:
product/list?attributes=test1:12,3&attributes=test1:test2
Run Code Online (Sandbox Code Playgroud)
但是,列表属性也将包含两个元素,“test1:12”和“3”,调用方式如下:
product/list?attributes=test1:12,3
Run Code Online (Sandbox Code Playgroud)
这样做的原因是,在第一种情况下,Spring 将在第一种情况下使用 ArrayToCollectionConverter。在第二种情况下,它将使用 StringToCollectionConverter,它将使用“,”作为分隔符拆分参数。
如何配置 Spring Boot 以忽略参数中的逗号?如果可能,解决方案应该是全球性的。
我们尝试过的:
这个问题对我们不起作用,因为我们有一个 List 而不是数组。此外,这只是控制器本地解决方案。
我也尝试添加此配置:
@Bean(name="conversionService")
public ConversionService getConversionService() {
ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean();
bean.setConverters(Collections.singleton(new CustomStringToCollectionConverter()));
bean.afterPropertiesSet();
return bean.getObject();
}
Run Code Online (Sandbox Code Playgroud)
其中 CustomStringToCollectionConverter 是 Spring StringToCollectionConverter 的副本,但没有拆分,但是,仍然优先调用 Spring 转换器。
凭直觉,我还尝试将“mvcConversionService”用作 bean 名称,但这也没有改变任何内容。
您可以删除 StringToCollectionConverter 并将其替换为您自己的WebMvcConfigurerAdapter.addFormatters(FormatterRegistry registry)方法:
像这样的东西:
@Configuration
public class MyWebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.removeConvertible(String.class,Collection.class);
registry.addConverter(String.class,Collection.class,myConverter);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3096 次 |
| 最近记录: |