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.

对于此类情况,基于配置的转换器自动应用类型转换。默认情况下,支持简单类型(intlongDate 等)。可以通过 WebDataBinder 自定义类型转换(参见 DataBinder)或通过 FormattersFormattingConversionService 注册。参见 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 的情况下被视为缺失值。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.

从 5.3 开始,即使在类型转换之后,也会强制执行非空参数。如果你的处理程序方法打算也接受一个空值,则可以将你的参数声明为 @Nullable,也可以在相应的 @RequestParam 等注释中将其标记为 required=false。这是一个最佳实践,也是在 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 @Nullable or mark it as required=false in the corresponding @RequestParam, etc. annotation. This is a best practice and the recommended solution for regressions encountered in a 5.3 upgrade.

或者,你还可以专门处理必需的 @PathVariable 中产生的 MissingPathVariableException。转换后的空值将被视为原始空值,因此将引发相应的 Missing…​Exception 变体。

Alternatively, you may specifically handle e.g. the resulting MissingPathVariableException in the case of a required @PathVariable. A null value after conversion will be treated like an empty original value, so the corresponding Missing…​Exception variants will be thrown.