Type Conversion

如果将参数声明为 String 以外的内容,则表示基于字符串的请求输入的一些带注解的控制器方法参数(例如 @RequestParam@RequestHeader@PathVariable@MatrixVariable@CookieValue)可能需要类型转换。

Some annotated controller method arguments that represent String-based request input (for example, @RequestParam, @RequestHeader, @PathVariable, @MatrixVariable, and @CookieValue) can require type conversion if the argument is declared as something other than String.

对于此类情况,将根据配置的转换器自动应用类型转换。默认情况下,支持简单类型(例如 intlongDate 等等)。可以通过 WebDataBinder 自定义类型转换(请参阅 DataBinder)或通过 FormattingConversionService 注册 Formatters(请参阅 Spring Field Formatting)。

For such cases, type conversion is automatically applied based on the configured converters. By default, simple types (such as int, long, Date, and others) are supported. Type conversion can be customized through a WebDataBinder (see DataBinder) or by registering Formatters with the FormattingConversionService (see Spring Field Formatting).

类型转换中的一个实际问题是对空字符串源值的处理。此类值会在结果类型转换后变为 null 的情况下被视为缺失值。LongUUID 和其他目标类型的情况可能如此。如果你想允许注入 null,则可以使用参数注释上的 required 标志,或将参数声明为 @Nullable

A practical issue in type conversion is the treatment of an empty String source value. Such a value is treated as missing if it becomes null as a result of type conversion. This can be the case for Long, UUID, and other target types. If you want to allow null to be injected, either use the required flag on the argument annotation, or declare the argument as @Nullable.