java - 无法在 Spring Boot 中使用自定义请求类中的存储库进行请求验证

标签 java spring spring-boot spring-data-jpa spring-validation

所以我试图在 UserCreateRequest 类中验证 emailname@Wired 不起作用并且 userRepository 为 null

UserCreateRequest.java:

@Getter
@Setter
@Component
public class UserCreateRequest {

    private UserRepository userRepository;

    public UserCreateRequest() {
    }

    @Autowired
    public UserCreateRequest(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @NotBlank(message = "Name is mandatory")
    @Size(min = 2, max = 20, message = "Name should be between 2 and 20 characters")
    private String name;


    @NotBlank(message = "Email is mandatory")
    @Email(message = "Email should be valid")
    private String email;

    @NotNull(message = "Date of birth is mandatory")
    @DateFormatRule(message = "Date of birth should be in yyyy-MM-dd format")
    private String dob;

    public User validated() {
        if (userRepository.findUserByEmail(email).isPresent()) {
            throw new RuntimeException("Email already exists");
        }
        if (userRepository.findUserByName(name).isPresent()) {
            throw new RuntimeException("Name already exists");
        }


        User user = new User();
        user.setName(name);
        user.setEmail(email);
        user.setDob(LocalDate.parse(dob));

        return user;
    }
}

UserController.java:

@PostMapping
public ResponseEntity<User> addUser(@Valid @RequestBody UserCreateRequest userCreateRequest) {

    User validatedData = userCreateRequest.validated();

    User createdUser = this.userService.addUser(validatedData);

    return ResponseEntity.ok(createdUser);
}

发送请求时遇到错误:

(ThreadPoolExecutor.java:659)\n\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\n\tat java.base/java.lang.Thread.run(Thread.java:1623)\n",
    "message": "Cannot invoke \"com.test.restapi.repository.UserRepository.findUserByEmail(String)\" because \"this.userRepository\" is null",
    "path": "/api/students"

我想检查数据库,如果用户nameemail已经存在于请求类中,而不是从 Controller 中检查。

有没有办法在UserCreateRequest类中使用userRepository

我找不到我正在寻找的确切解决方案

最佳答案

UserCreateRequest 不是 spring 管理的组件,它是通过将请求负载映射到类来创建的。您可以:

  1. 通过在 Controller 中注入(inject)上下文来手动 Autowiring 存储库 - 只是不要这样做,您已经通过向 dto 添加业务逻辑(验证和映射)来混合职责。
  2. 创建验证注释以应用于字段 - @UniqueName@UniqueEmail。他们的 validator 可以轻松地制作成 spring 管理的组件。

关于java - 无法在 Spring Boot 中使用自定义请求类中的存储库进行请求验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76930510/

相关文章:

java - 比较两个 json 结构并得到不匹配的变化

angularjs - Stormpath Spring Boot 重定向循环

java - Ctrl+B 键盘绑定(bind)如何工作?

java - 将 Jsonpath 输出映射到 POJO 列表

java - Spring BeanFactory 作为 Swing 应用程序中的单例

java - 几分钟后,Spring Boot 停止解析 View

java - 从hibernate拦截器获取实体字段注释

java - CRUDrepository(spring boot)中自定义方法的问题

java - Maven 在拥有主类的同时强制使用特定的 Java 版本

java - 如何使用redis或memcached配置tomcat6或7共享 session ?