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

lymgl2op  于 2023-11-19  发布在  Spring
关注(0)|答案(1)|浏览(126)

因此,我试图在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已经存在从请求类,没有检查,从控制器。
有没有办法像这样在UserCreateRequest类中使用userRepository
我找不到我想要的确切的解决方案

fzsnzjdm

fzsnzjdm1#

UserCreateRequest不是spring管理的组件,它是通过将请求payloadMap到类来创建的。您可以:
1.通过在控制器中注入上下文来手动自动连接存储库-不要这样做,通过向dto添加业务逻辑(验证和Map),您已经混合了职责。
1.创建验证注解以应用于字段-@UniqueName@UniqueEmail。它们的验证器可以轻松地制作成spring管理的组件。

相关问题