【问题标题】:Cannot invoke findByEmail because "this.userRepository" is null error无法调用 findByEmail,因为“this.userRepository”为空错误
【发布时间】:2021-03-22 23:30:28
【问题描述】:

我不断收到无法调用“com.***.repositories.UserRepository.findByEmail(String)”,因为每次我尝试处理我的 /register 方法时“this.userRepository”都是空错误。

我无法弄清楚为什么代码会显示为 null。

控制器 -

@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);
}

【问题讨论】:

  • 您显示的代码中没有userRepository。更一般地,消除@Autowired 字段;它们是臭名昭著的问题根源。用构造函数参数替换它们(如果你只有一个构造函数,Spring 会自动理解这些,不需要注释)。
  • @chrylis-cautiouslyoptimistic- 我更新了我的代码,但仍然遇到同样的错误
  • 您粘贴的代码在存储库引用或控制器类中所有依赖项的参数化构造函数中没有@Autowired

标签: java spring-boot api axios registration


【解决方案1】:

只需将@Autowired 添加到您希望在春季自动装配的相关字段中。

更改您的代码

   @Autowired
    UserService userService;
    UserRepository userRepository;
    AuthenticationTokenRepository authenticationTokenRepository;

   @Autowired
    UserService userService;

   @Autowired
    UserRepository userRepository;

   @Autowired
    AuthenticationTokenRepository authenticationTokenRepository;

【讨论】:

    【解决方案2】:

    我有两个解决方案。

    1. 从字段中消除@Autowired; 用构造函数参数替换它们(如果你只有一个构造函数,Spring 会自动理解这些,不需要 @Autowired 注释)。

    2. 在“配置类”中使用@Autowired 创建字段注入,例如(安全配置),并使用参数化构造函数创建目标类对象并传递注入的字段。

    【讨论】:

      猜你喜欢
      • 2021-08-29
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-18
      • 2022-11-19
      相关资源
      最近更新 更多