首页 > 解决方案 > Spring Boot 2 和方法参数验证

问题描述

我创建了以下服务接口:

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);

}

但以下调用:

userService.create(telegramId, "Mike", null);

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

标签: javaspringspring-bootspring-validator

解决方案


我在这个问题上玩了一会儿。

您的代码对我来说看起来不错:确保 的实现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);
}

服务实施

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;
    }
}

测试用例

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(""));
    }

}

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

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

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


推荐阅读