How to bind request params without setters?

后端 未结 2 1253
故里飘歌
故里飘歌 2021-01-02 03:33

I have a simple controller with a GET handler that accepts an object to bind request parameters:

@RestController
@RequestMapping(\"/test\")
public class Samp         


        
相关标签:
2条回答
  • 2021-01-02 03:59

    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();
    }
    
    0 讨论(0)
  • Spring Boot libraries depend on Jackson (spring-boot-starter-web<-spring-boot-starter-json<-jackson libraries), so one can use its annotations to control json bindings.

    @JsonCreator-annotated constructors or static methods allow to instantiate objects without explicit setters:

    @JsonCreator
    public RequestParams(@JsonProperty("param1") String param1, 
                         @JsonProperty("param2") String param2) {
        this.param1 = param1;
        this.param2 = param2;
    }
    

    Documentation

    • https://fasterxml.github.io/jackson-annotations/javadoc/2.8/com/fasterxml/jackson/annotation/JsonCreator.html
    • https://github.com/FasterXML/jackson-annotations/wiki
    0 讨论(0)
提交回复
热议问题