【问题标题】:How to prevent Spring MVC from interpreting commas when converting to a Collection in Spring Boot?在 Spring Boot 中转换为 Collection 时如何防止 Spring MVC 解释逗号?
【发布时间】:2017-06-26 12:16:47
【问题描述】:

我们基本上和this question有同样的问题,但是对于列表和另外,我们正在寻找一个全局的解决方案。

目前我们有一个这样定义的 REST 调用:

@RequestMapping
@ResponseBody
public Object listProducts(@RequestParam(value = "attributes", required = false) List<String> attributes) {

调用正常,当这样调用时,列表属性将包含两个元素“test1:12,3”和“test1:test2”:

product/list?attributes=test1:12,3&attributes=test1:test2

但是,列表属性也将包含两个元素,“test1:12”和“3”,调用如下:

product/list?attributes=test1:12,3

这样做的原因是,在第一种情况下,Spring 将在第一种情况下使用 ArrayToCollectionConverter。在第二种情况下,它将使用 StringToCollectionConverter,它将使用“,”作为分隔符分割参数。

如何配置Spring Boot忽略参数中的逗号?如果可能,解决方案应该是全局的。

我们的尝试:

This question 对我们不起作用,因为我们有一个 List 而不是数组。此外,这只是一个控制器本地解决方案。

我也试过添加这个配置:

@Bean(name="conversionService")
public ConversionService getConversionService() {
    ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean();
    bean.setConverters(Collections.singleton(new CustomStringToCollectionConverter()));
    bean.afterPropertiesSet();
    return bean.getObject();
}

其中 CustomStringToCollectionConverter 是 Spring StringToCollectionConverter 的一个副本,但是没有拆分,Spring 转换器仍然被优先调用。

凭直觉,我也尝试将“mvcConversionService”作为 bean 名称,但这也没有改变任何东西。

【问题讨论】:

    标签: java spring spring-mvc spring-boot


    【解决方案1】:

    您可以在 WebMvcConfigurerAdapter.addFormatters(FormatterRegistry registry) 方法中删除 StringToCollectionConverter 并用您自己的替换它:

    类似这样的:

    @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);
      }
    }
    

    【讨论】:

    • 您能否为单个端点提出类似的解决方案?
    【解决方案2】:

    对我来说,即使没有添加新转换器的行,它也能正常工作,但因为@Strelok 没有提供如何编写新转换器的示例,这里是一个完整的解决方案:

    @Configuration
    class WebMvcConfig extends WebMvcConfigurerAdapter {
    
        @Override
        public void addFormatters(FormatterRegistry registry) {
            registry.removeConvertible(String.class, Collection.class);
            registry.addConverter(String.class, Collection.class, noCommaSplitStringToCollectionConverter());
        }
    
        public Converter<String, Collection> noCommaSplitStringToCollectionConverter() {
            return Collections::singletonList;
        }
    
    }
    

    我的版本是经过修改和更新的字符串到数组转换器之一,您可以在此处找到: How to disable spring boot parameter split

    【讨论】:

      猜你喜欢
      • 2011-06-27
      • 2018-04-04
      • 2019-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      相关资源
      最近更新 更多