Cannot invoke findByEmail because "this.userRepository" is null error
Asked Answered
E

3

5

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);
}
Eastertide answered 22/3, 2021 at 23:30 Comment(3)
There's no userRepository in the code you showed. More generally, eliminate @Autowired fields; they're a notorious source of problems. Replace them with constructor parameters (Spring understands these automatically with no need for annotations if you have only one constructor).Resiniferous
@chrylis-cautiouslyoptimistic- I updated my code and am still getting the same errorEastertide
The code you have pasted, doesn't have @Autowired on repository reference or parameterized constructor for all the dependencies in your controller class.Case
N
8

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;
Neoteric answered 23/3, 2021 at 0:40 Comment(0)
C
0

I have two solutions for this.

  1. Eliminate @Autowired from fields; Replace them with constructor parameters (Spring understands these automatically with no need for @Autowired annotations if you have only one constructor).

  2. Create field injection with @Autowired in you "config class" eg(Security config) and create your target class object with parameterized constructor and pass the injected filed.

Continuum answered 22/10, 2021 at 5:57 Comment(0)
M
0

try add below property to your application.properties file.

spring.jpa.properties.javax.persistence.validation.mode=none
Marlow answered 22/9, 2022 at 14:3 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.