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)
显然这是某种代码味道.但是,因为我确实需要验证since并until在使用它们来查询服务/ DAO之前,我不知道我应该在哪里提取这些代码?
有什么建议?
Run Code Online (Sandbox Code Playgroud)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
}
Run Code Online (Sandbox Code Playgroud)