gpt4 book ai didi

java - 在 Spring Boot 中转换为 Collection 时如何防止 Spring MVC 解释逗号?

转载 作者:搜寻专家 更新时间:2023-11-01 02:58:57 25 4
gpt4 key购买 nike

我们基本上遇到了与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对我们不起作用,因为我们有一个列表而不是数组。此外,这只是一个 Controller 本地解决方案。

我也尝试添加这个配置:

@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 名称,但这也没有改变任何东西。

最佳答案

您可以在 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);
}
}

关于java - 在 Spring Boot 中转换为 Collection 时如何防止 Spring MVC 解释逗号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42120588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com