在我的 Spring Boot 应用程序中,我有一些控制器接受日期作为查询参数:
@RestController
public class MyController {
@GetMapping
public ResponseEntity<?> getDataByDate(
@RequestParam(value = "date") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
final LocalDate date) {
return ResponseEntity.ok();
}
}
这效果很好,我什至可以使用将参数标记为可选@RequestParam(value = "date", required = false)
然后使用Optional<LocalDate>
。 Spring 将处理所有这些,并在参数丢失时传递一个空的Optional。
由于我有几个使用日期作为查询参数的控制器,我想为所有控制器配置此行为LocalDate
查询参数。我已经尝试过spring.mvc.date-pattern
财产,但它似乎只适用于java.util.Date
.
因此,在搜索网络后,我想到的最好的方法是ControllerAdvice
我从此采用了answer https://stackoverflow.com/a/43726183/5391954。这个解决方案的问题是,无法处理Optional<LocalDate>
不再了。感觉这是在 Spring Boot 中配置行为的错误方法。
所以我的问题是:如何全局配置模式LocalDate
在Spring Boot中以惯用的方式用作查询参数?
目前这不容易实现(例如通过设置一个简单的配置属性),请参阅#5523 https://github.com/spring-projects/spring-boot/issues/5523。到目前为止我发现的最好的解决方案是注册一个Formatter<LocalDate>
。这也适用于建模为的可选参数Optional<LocalDate>
:
@Bean
public Formatter<LocalDate> localDateFormatter() {
return new Formatter<LocalDate>() {
@Override
public LocalDate parse(String text, Locale locale) throws ParseException {
return LocalDate.parse(text, DateTimeFormatter.ISO_DATE);
}
@Override
public String print(LocalDate object, Locale locale) {
return DateTimeFormatter.ISO_DATE.format(object);
}
};
}
当我的建议出现时,可以使用配置属性来设置它#9930 https://github.com/spring-projects/spring-boot/pull/9930已合并。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)