简体   繁体   中英

Spring boot rest api not working with Valid annotation

When i call the following api it gives 400 bad request even if we given valid data with request body. If i remove the @Valid annotation then it works fine. can any one help me here what is going wrong.

I am sending following request body with Postman { "x": "a", "y": "b" }

 import javax.validation.Valid;
    import org.springframework.validation.annotation.Validated;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import com.magicsoftware.restapi.exception.TestPOJO;
    import io.swagger.v3.oas.annotations.parameters.RequestBody;

@RestController
@Validated
@RequestMapping(path = "/Test")
public class TestController {

    @GetMapping(value = "/test1")
    public String test1(@Valid @RequestBody TestPOJO tpj) {
        if (tpj instanceof TestPOJO) {
            System.out.println("Correct data format passed ");
        }
        return "working1";

    }
}

    import javax.validation.constraints.NotNull;

public class TestPOJO {
    @NotNull(message="X should not be null")
    private String x;

    @NotNull(message="Y should not be null")
    private String y;


    public String getX() {
        return x;
    }
    public void setX(String x) {
        this.x = x;
    }
    public String getY() {
        return y;
    }
    public void setY(String y) {
        this.y = y;
    }   
}

You are importing RequestBody from io.swagger.v3.oas.annotations.parameters.RequestBody; but it shoud be imported from

org.springframework.web.bind.annotation.RequestBody;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM