Issue
I keep receiving a Cannot invoke "com.***.repositories.UserRepository.findByEmail(String)" because "this.userRepository" is null error everytime I try to process my /register method.
I can't figure out why the code is coming across as 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 call -
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);
})
}
My UserRepository -
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByEmail(String email);
}
Solution
Simply add @Autowired to your related fields you want to get Autowired by spring.
Change your code from
@Autowired
UserService userService;
UserRepository userRepository;
AuthenticationTokenRepository authenticationTokenRepository;
to
@Autowired
UserService userService;
@Autowired
UserRepository userRepository;
@Autowired
AuthenticationTokenRepository authenticationTokenRepository;
Answered By - fo0
Answer Checked By - Pedro (JavaFixing Volunteer)