【问题标题】:@RequestParam annotation in Spring MVC with YearMonth valueSpring MVC 中的 @RequestParam 注释,带有 YearMonth 值
【发布时间】:2018-05-03 08:44:44
【问题描述】:

我正在尝试获取以下格式“2018-01”的查询参数以用作 YearMonth (java.time) 对象。

在我的控制器中,我有以下参数:

@RequestParam(value = "start") @DateTimeFormat(pattern = "yyyy-MM") YearMonth start

但我收到以下错误: 无法将类型 [java.lang.String] 的值转换为所需类型 [java.time.YearMonth];嵌套异常是 java.lang.IllegalStateException:无法将类型 [java.lang.String] 的值转换为所需类型 [java.time.YearMonth]:找不到匹配的编辑器或转换策略

编辑:
根据此链接:https://jira.spring.io/browse/SPR-13518,从 4.2.4 版本开始支持 java.time.YearMonth 转换,我使用的是 spring 版本 4.3.3.RELEASE

【问题讨论】:

  • 你能用LocalDate代替YearMonth吗? (我没用过@DateTimeFormat,只是一个想法)
  • 查看错误信息的末尾:no matching editors or conversion strategy found。这意味着 Spring 找不到将您的 String 转换为 YearMonth 对象的属性编辑器或转换器。

标签: java spring-mvc


【解决方案1】:

不知道 @DateTimeFormatter 注解是否支持 YearMonth 进行隐式转换。但是

您始终可以像这样为此 YearMonth 类型注册自定义转换器:

@Configuration
@EnableMvc 
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new YearMonthConverter());
    }
}

将 YearMonthConverter 定义为:

public class YearMonthConverter implements Converter<String, YearMonth> {

    @Override
    public YearMonth convert(String text) {
        return YearMonth.parse(text, DateTimeFormatter.ofPattern("yyyy-MM"));
    }
}

您可以放心进行隐式转换。

【讨论】:

  • 我本来希望使用 Spring 注释,因为根据 jira.spring.io/browse/SPR-13518,它从 4.2.4 版本开始支持。无论如何,我尝试了您的解决方案并且它有效。
  • 您应该编辑您的答案以在 WebMvcConfig 类上添加 Configuration 注释,以防其他人可能需要使用您的答案
猜你喜欢
  • 2010-10-04
  • 1970-01-01
  • 1970-01-01
  • 2022-08-16
  • 2016-01-27
  • 1970-01-01
  • 2021-02-09
  • 2015-03-13
  • 2011-12-21
相关资源
最近更新 更多