Spring rest controller does not validate my DTO

Viewed 48

I have this request and response:

@Data
public class TestRequestDto {
    @Min(7)
    private String name;
}

@Data
public class TestResponseDto {
    private String response;
}

And I have a controller:

package com.example.validation.demo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@Slf4j
@RestController
public class TetController {

    @PostMapping("/test")
    public TestResponseDto getTestResponseDto(@Valid @RequestBody TestRequestDto request){
        log.info(request.getName());
        TestResponseDto response = new TestResponseDto();
        response.setResponse("response");
        return response;
    }
}

I send a post request({"name":"test"}) with an invalid name but it works. What am I doing wrong?

1 Answers

Starting with Boot 2.3, we also need to explicitly add the spring-boot-starter-validation dependency

Related