问题描述
我有一个带有GET处理程序的简单控制器,它接受一个绑定请求参数的对象:
I have a simple controller with a GET handler that accepts an object to bind request parameters:
@RestController
@RequestMapping("/test")
public class SampleController {
@GetMapping
public SomeResponse find(RequestParams params) {
// some code
}
}
RequestParams
是一个简单的POJO类:
The RequestParams
is a simple POJO class:
public class RequestParams {
private String param1;
private String param2;
// constructor, getter, and setters
}
Everthing工作正常,但我想摆脱设置者,使对象不可变为公共使用。在 @RequestMapping
处理程序方法直到Spring 5.0.2,我们读到
可能的有效方法参数是:
Everthing works fine, but I would like to get rid of the setters to make the object immutable to public use. In the documentation for @RequestMapping
handler method up to Spring 5.0.2, we read thatpossible valid method arguments are:
是否有可能以某种方式覆盖默认的Spring Boot配置,以便请求参数使用反射而不是使用setter绑定到类属性?
Is it possible to somehow override the default Spring Boot configuration so that request parameters are bound to class properties using reflection and not with setters?
更新2018
在Spring的文档的更高版本中,引用的语句已被重新定义,并且没有更长时间包含有关将请求参数绑定到字段的信息。
In the later versions of Spring's documentation, the quoted statement has been rephrased and no longer contain information about binding request parameters directly to fields.
推荐答案
除了JSON注释建议b y @jihor你可以尝试使用自定义,将以下代码添加到控制器或类跨越多个控制器的功能。
In addition to JSON annotations suggested by @jihor you can try to use custom Web Data binder, adding following code to your controller or to Controller Advice class to span functionality across multiple controllers.
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.initDirectFieldAccess();
}
这篇关于如何在没有setter的情况下绑定请求参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!