因此,我试图在UserCreateRequest
类中验证email
和name
,但@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"
型
我想检查数据库,如果用户name
或email
已经存在从请求类,没有检查,从控制器。
有没有办法像这样在UserCreateRequest
类中使用userRepository
?
我找不到我想要的确切的解决方案
1条答案
按热度按时间fzsnzjdm1#
UserCreateRequest
不是spring管理的组件,它是通过将请求payloadMap到类来创建的。您可以:1.通过在控制器中注入上下文来手动自动连接存储库-不要这样做,通过向dto添加业务逻辑(验证和Map),您已经混合了职责。
1.创建验证注解以应用于字段-
@UniqueName
,@UniqueEmail
。它们的验证器可以轻松地制作成spring管理的组件。