gpt4 book ai didi

java - Spring Boot 2及方法参数校验

转载 作者:行者123 更新时间:2023-11-29 04:06:08 25 4
gpt4 key购买 nike

我创建了以下服务接口(interface):

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

通过 @NotNullisBot 参数的验证。如何正确配置 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

喂!

关于java - Spring Boot 2及方法参数校验,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58554617/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com