我正在使用 Spring 3.2.18(我知道,它很旧)和 Spring MVC 一起运行。我的问题是,当数组中实际上只有一项但有逗号时,至少有一个默认请求参数转换(字符串 -> 列表)会失败。这是因为 Spring 内置的默认转换会将其视为逗号分隔的列表。
我不使用Spring Boot,所以请避免专门参考使用它的解决方案的答案。
我尝试将 @PostConstruct 方法添加到 @Confuguration 类,如下所示:
@Configuration
public class MyConfig {
@Autowired
private ConfigurableEnvironment env;
@PostConstruct
public void removeConverters() {
ConfigurableConversionService conversionService = env.getConversionService();
conversionService.removeConvertible(String.class, Collection.class);
}
}
这会在启动时运行,但仍然会发生损坏的转换。我在这个方法中放置了一个断点,并且在启动时仅调用一次。我验证它删除了与 String -> Collection 签名匹配的转换器。
以下方法有效,但是当我在 @InitBinder 方法中放置断点时,它的行为就像每个请求的每个请求参数都会调用一次。
@ControllerAdvice
public class MyController {
@InitBinder
public void initBinder(WebDataBinder binder) {
GenericConversionService conversionService = (GenericConversionService) binder.getConversionService();
conversionService.removeConvertible(String.class, Collection.class);
}
}
正如我所说,第二个可行,但是对于对该方法发出的每个请求都必须删除有问题的转换器是没有意义的 - 更不用说对于该方法采用的每个请求参数了。
有人可以告诉我为什么这只在删除非常多余的情况下才有效吗?更好的是,请告诉我如何错误地进行一次性应用程序范围删除。
@Jon 我相信你的第二个可行,但它会从全局转换服务中删除可转换类型。你可以测试看看。