在Spring控制器中使用日期参数的最佳实践?

Fre*_*Pym 5 java parameters spring spring-mvc

在编写了几个后端API之后,我发现以下代码几乎在每个需要按日期过滤数据的方法中都重复:

@GetMapping(value="/api/test")
@ResponseBody
public Result test(@RequestParam(value = "since", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate since,
                   @RequestParam(value = "until", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate until) {
    // Date validation code I want to eliminate
    since = ObjectUtils.defaultIfNull(since, DEFAULT_SINCE_DATE);
    until = ObjectUtils.defaultIfNull(until, LocalDate.now().plusDays(1));
    if(since.isAfter(until)) {
        throw new SinceDateAfterUntilDateException();
    }

    // Do stuff
}
Run Code Online (Sandbox Code Playgroud)

显然这是某种代码味道.但是,因为我确实需要验证sinceuntil在使用它们来查询服务/ DAO之前,我不知道我应该在哪里提取这些代码?

有什么建议?

Ami*_*har 0

  1. 实现 org.springframework.core.convert.converter.Converter; 界面。
  2. 注册 Spring 转换服务。
  3. 在您的控制器中使用共享示例代码如下:
public class MyCustomDateTypeConverter implements Converter<String, LocalDate> {

  @Override
  public LocalDate convert(String param) {
      //convert string to DateTime
      return dateTiemObjectCreatedfromParam;
  }

}
Run Code Online (Sandbox Code Playgroud)
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">  <property name="converters">    <list>
        <bean class="com.x.y.z.web.converters.MyCustomDateTypeConverter"/>  </list>     </property> 
</bean>


<mvc:annotation-driven conversion-service="conversionService">

</mvc:annotation-driven>


public Result test(LocalDate since,LocalDate until) {

    since = ObjectUtils.defaultIfNull(since, DEFAULT_SINCE_DATE);
    until = ObjectUtils.defaultIfNull(until, LocalDate.now().plusDays(1));
    if(since.isAfter(until)) {
        throw new SinceDateAfterUntilDateException();
    }

    // Do stuff
}
Run Code Online (Sandbox Code Playgroud)