java – spring-cloud-feign Client和带有Date类型的@RequestParam
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – spring-cloud-feign Client和带有Date类型的@RequestParam,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2343字,纯文字阅读大概需要4分钟。
内容图文
这次我正在使用Declarative REST Client,在一些Spring Boot App中使用Feign.
我想要实现的是调用我的一个REST API,它看起来像:
@RequestMapping(value = "/customerslastvisit", method = RequestMethod.GET)
public ResponseEntity customersLastVisit(
@RequestParam(value = "from", required = true) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date from,
@RequestParam(value = "to", required = true) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date to) {
正如您所看到的,API接受带有from和to params的调用格式为(yyyy-MM-dd)
为了调用该API,我准备了以下@FeignClient:
@FeignClient("MIIA-A")
public interface InboundACustomersClient {
@RequestMapping(method = RequestMethod.GET, value = "/customerslastvisit")
ResponseEntity customersLastVisit(
@RequestParam(value = "from", required = true) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date from,
@RequestParam(value = "to", required = true) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date to);
}
一般来说,几乎是复制粘贴.现在在我的启动应用程序的某个地方,我使用它:
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
ResponseEntity response = inboundACustomersClient.customersLastVisit(formatter.parse(formatter.format(from)),
formatter.parse(formatter.format(to)));
而且,我得到的回报是
nested exception is
org.springframework.core.convert.ConversionFailedException: Failed to
convert from type [java.lang.String] to type
[@org.springframework.web.bind.annotation.RequestParam
@org.springframework.format.annotation.DateTimeFormat java.util.Date]
for value ‘Sun May 03 00:00:00 CEST 2015’;nested exception is java.lang.IllegalArgumentException: Unable to
parse ‘Sun May 03 00:00:00 CEST 2015’
所以,问题是,我对请求做了什么错误,它在发送到我的API之前没有解析为“仅日期”格式?或者它可能是一个纯粹的Feign lib问题?
解决方法:
您应该创建并注册一个假格式化程序来自定义日期格式
@Component
public class DateFormatter implements Formatter<Date> {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
@Override
public Date parse(String text, Locale locale) throws ParseException {
return formatter.parse(text);
}
@Override
public String print(Date date, Locale locale) {
return formatter.format(date);
}
}
@Configuration
public class FeignFormatterRegister implements FeignFormatterRegistrar {
@Override
public void registerFormatters(FormatterRegistry registry) {
registry.addFormatter(new DateFormatter());
}
}
内容总结
以上是互联网集市为您收集整理的java – spring-cloud-feign Client和带有Date类型的@RequestParam全部内容,希望文章能够帮你解决java – spring-cloud-feign Client和带有Date类型的@RequestParam所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。