gpt4 book ai didi

java - 无法调用 findByEmail 因为 "this.userRepository"是空错误

转载 作者:行者123 更新时间:2023-12-04 07:54:56 31 4
gpt4 key购买 nike

每次我尝试处理我的/register 方法时,我都会收到 Cannot invoke "com.***.repositories.UserRepository.findByEmail(String)"因为 "this.userRepository"is null 错误。

我不明白为什么代码显示为空。

Controller -

@Controller
@RestController
@RequestMapping("/api/v1")
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class AuthenticationController {

@Autowired
UserService userService;
UserRepository userRepository;
AuthenticationTokenRepository authenticationTokenRepository;

@PostMapping(value = "/register")
public ModelAndView registerUser(ModelAndView modelAndView, User user) {
User existingUser = userRepository.findByEmail(user.getEmail());
if (existingUser != null) {
modelAndView.addObject("message", "This email already exists!");
modelAndView.setViewName("error");
} else {
userRepository.save(user);

AuthenticationToken authenticationToken = new AuthenticationToken(user);
authenticationTokenRepository.save(authenticationToken);

SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setTo(user.getEmail());
mailMessage.setSubject("Complete Registration!");
mailMessage.setFrom("***@gmail.com");
mailMessage.setText("To confirm your account, please click here : "
+ "http://localhost:8080/confirm-account?token=" + authenticationToken.getConfirmationToken());

emailSenderService.sendEmail(mailMessage);
modelAndView.addObject("email", user.getEmail());
modelAndView.setViewName("successfulRegisteration");
}
return modelAndView;
}

}

Axios 调用 -

submit() {
let formData = new FormData();
formData.set("firstName" , this.firstName)
formData.set("lastName", this.lastName)
formData.set("email", this.email)
formData.set("password", this.password)
formData.set("captchaToken", this.captchaToken)
formData.set("agreedToTermsOfService", true)
axios.post("http://localhost:8080/api/v1/register", formData,
{headers: {'Content-Type': 'application/json'}})
.then(res => {
if (res.status === 200) {
this.$router.push('/register-complete');
} else {
console.log(res.data.code);
}
})
.catch(function (err) {
console.log(err);
})
}

我的用户资料库-

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByEmail(String email);
}

最佳答案

只需将@Autowired 添加到您希望在 spring 之前 Autowiring 的相关字段。

更改您的代码

   @Autowired
UserService userService;
UserRepository userRepository;
AuthenticationTokenRepository authenticationTokenRepository;

   @Autowired
UserService userService;

@Autowired
UserRepository userRepository;

@Autowired
AuthenticationTokenRepository authenticationTokenRepository;

关于java - 无法调用 findByEmail 因为 "this.userRepository"是空错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66755214/

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