@InitBinder注解用于自定义将请求参数类型转换为控制器的过程。这样,甚至可以在执行请求之前调用该方法,从而有机会预处理请求数据、验证、格式化或执行任何必要的操作。
类@Controller或@ControllerAdvice类可以具有可以使用@InitBinder进行预处理的方法。对于DataBinder@Controller自定义仅在控制器内本地应用。 For适用于所有控制器。@ControllerAdvice
让我们使用@InitBinder将请求属性转换为类型LocalDate并LocalDateTime作为自定义属性。
让我们创建一个名为 的类LocalDateTimeRequestConfig,它将接收注释@ControllerAdvice并具有一个用 注释的方法@InitBinder,如下所示:
@ControllerAdvice |
使用WebDataBinder参数,我们将使用registerCustomEditor().对于我们的示例,我们将为 创建一个转换器LocalDate,如下所示:
binder.registerCustomEditor( |
我们将为该类型添加转换器LocalDateTime,最终的实现如下所示:
@ControllerAdvice
public class LocalDateTimeRequestConfig {
@InitBinder
public void initBinder(WebDataBinder binder) {
// convert string into LocalDate type
binder.registerCustomEditor(
LocalDate.class,
new PropertyEditorSupport() {
@Override
public void setAsText(String localDateAsString) throws IllegalArgumentException {
setValue(LocalDate.parse(localDateAsString));
}
}
);
// convert string into LocalDateTime type
binder.registerCustomEditor(
LocalDateTime.class,
new PropertyEditorSupport() {
@Override
public void setAsText(String localDateTimeAsString) throws IllegalArgumentException {
setValue(LocalDateTime.parse(localDateTimeAsString));
}
}
);
}
}
现在,表示端点请求的所有对象及其属性都被标记为LocalDate并将LocalDateTime自动转换,除了集中在单个类中之外,无需在控制器内部或其他任何地方进行此转换。
如果您想查看此类的示例,可以在此处查看。
结论
在使用 @ControllerAdvice 的情况下,使用 @InitBinder 可以从控制器内的请求中移除重复的类型转换代码,并将其集中到一个类中,从而提高代码的质量和可维护性。