java - 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
?
解决方案
我在这个问题上玩了一会儿。
您的代码对我来说看起来不错:确保 的实现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
!
推荐阅读
- mongodb - 猫鼬。按数组中的最后一个对象排序
- android - 在多模块 Android 项目中找不到 Kotlin 类型别名
- sql - 对 PostgreSQL 运行总结果进行分组
- database - 颤动,从 sqflite 获取项目并使用 ONTAP 在列表视图中显示
- jsf - 从 J2EE 安全转发获取原始 url
- python - Pandas 按顺序值分组
- c++ - CMAKE_CXX_CLANG_TIDY:避免 clang-diagnostic-error 中断构建
- swift - Swift 4. 在继续执行之前等待 HealthKit HKQuery 的异步结果
- c# - C# GridView 行添加到错误的位置?
- powershell - 使用 powershell 登录 Auth0 (OWIN) 锁屏