Type Conversion
某些表示基于 String
的请求输入的带注释控制器方法参数(例如 @RequestParam
、@RequestHeader
、@PathVariable
、@MatrixVariable
和 @CookieValue
)在将参数声明为除 String
之外的其他内容时可能需要类型转换。
Some annotated controller method arguments that represent String
-based request input (such as
@RequestParam
, @RequestHeader
, @PathVariable
, @MatrixVariable
, and @CookieValue
)
can require type conversion if the argument is declared as something other than String
.
对于此类情况,基于配置的转换器自动应用类型转换。默认情况下,支持简单类型(int
,long
,Date
等)。可以通过 WebDataBinder
自定义类型转换(参见 DataBinder
)或通过 Formatters
向 FormattingConversionService
注册。参见 Spring Field Formatting。
For such cases, type conversion is automatically applied based on the configured converters.
By default, simple types (int
, long
, Date
, and others) are supported. You can customize
type conversion through a WebDataBinder
(see DataBinder
) or by registering
Formatters
with the FormattingConversionService
.
See Spring Field Formatting.
类型转换中的一个实际问题是对空字符串源值的处理。此类值会在结果类型转换后变为 null
的情况下被视为缺失值。Long
、UUID
和其他目标类型的情况可能如此。如果你想允许注入 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
.
从 5.3 开始,即使在类型转换之后,也会强制执行非空参数。如果你的处理程序方法打算也接受一个空值,则可以将你的参数声明为 As of 5.3, non-null arguments will be enforced even after type conversion. If your handler
method intends to accept a null value as well, either declare your argument as 或者,你还可以专门处理必需的 Alternatively, you may specifically handle e.g. the resulting |