写了几个后端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
}
显然这是某种代码味道。但是,由于在使用它们查询服务/DAO 之前我确实需要验证 since
和 until
,所以我不确定应该将这些代码提取到哪里?
有什么建议吗?
最佳答案
- 实现 org.springframework.core.convert.converter.Converter;界面。
- 注册 spring 转换服务。
- 在你的 Controller 中使用 下面分享示例代码:
public class MyCustomDateTypeConverter implements Converter<String, LocalDate> { @Override public LocalDate convert(String param) { //convert string to DateTime return dateTiemObjectCreatedfromParam; } }
<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
}
关于java - 在 Spring Controller 中使用日期参数的最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44409266/