Spring Boot 2 和方法参数验证

ale*_*oid 4 java spring spring-validator spring-boot

我创建了以下服务接口:

import javax.validation.constraints.NotBlank;

import org.springframework.lang.NonNull;
import org.springframework.validation.annotation.Validated;

@Validated
public interface UserService {

    User create(@NonNull Long telegramId, @NotBlank String name, @NonNull Boolean isBot);

}
Run Code Online (Sandbox Code Playgroud)

但以下调用:

userService.create(telegramId, "Mike", null);
Run Code Online (Sandbox Code Playgroud)

通过参数@NotNull验证isBot。如何正确配置 Spring Boot 和我的服务,以考虑@NonNull注释并防止参数情况下的方法执行null?

alm*_*777 5

我玩了一下这个问题。

您的代码对我来说看起来不错:确保 的实现UserService也存在验证注释。

确保允许 Spring 创建 Bean;它应该按您的预期工作。

例子

服务定义

import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

@Validated
public interface GreetingService {
    String greet(@NotNull @NotBlank String greeting);
}
Run Code Online (Sandbox Code Playgroud)

服务实施

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

@Service
public class HelloGreetingService implements GreetingService {

    public String greet(@NotNull @NotBlank String greeting) {
        return "hello " + greeting;
    }
}
Run Code Online (Sandbox Code Playgroud)

测试用例

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;

import javax.validation.ConstraintViolationException;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

@SpringBootTest
class HelloGreetingServiceTest {

    @Autowired
    private GreetingService helloGreetingService;

    @Test
    void whenGreetWithStringInput_shouldDisplayGreeting() {
        String input = "john doe";
        assertEquals("hello john doe", helloGreetingService.greet(input));
    }

    @Test
    void whenGreetWithNullInput_shouldThrowException() {
        assertThrows(ConstraintViolationException.class, () -> helloGreetingService.greet(null));
    }

    @Test
    void whenGreetWithBlankInput_shouldThrowException() {
        assertThrows(ConstraintViolationException.class, () -> helloGreetingService.greet(""));
    }

}
Run Code Online (Sandbox Code Playgroud)

测试用例对我来说是绿色的。

Github: https: //github.com/almac777/spring-validation-playground

来源: https: //www.baeldung.com/javax-validation-method-constraints

哈!