繁体   English   中英

不能调用工厂 class 因为它是 null?

[英]Cannot invoke factory class because it is null?

我有一个注册表格页面 index.html 供我正在构建的汽车租赁应用程序的用户使用

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
  <meta charset="UTF-8">
  <title>Register</title>
</head>
<body>
<form action="#" th:action="@{/register}" th:object="${user}"
        method="post">
  <p>User Name <input type="text" name="name"></p>
  <p>Password <input type="password" name="password"></p>
  <button type="submit">Register</button>
</form>
</body>
</html>

和相应的 controller class 我想使用工厂 class 调用新用户然后将其保存到 MySQL DB

Controller Class:

@Controller
public class IndexController {

    @Autowired
    private UserService userService;
    private CustomerFactory userFactory;
    private UserController controller;

    @GetMapping("/")
    public String registerForm(Model model){

        return "index";
    }

    @GetMapping("/car-list")
    public String carList(){
        return "index";
    }

    @PostMapping("/register")
    public String registerUser(@ModelAttribute User user){

        User u = userFactory.createUser(user.getName(), user.getPassword());
        //userService.saveUser(user);
        return "car-list";
    }
}

这是用户 class:

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "userID", nullable = false)
    private int userID;
    private String name;
    private String password;

    public User() {
    }
    public User(String name, String password) {
        this.name = name;
        this.password = password;
    }
    //getters setters and toString omitted
}

这是我的工厂 class:

public class CustomerFactory implements com.project.CS4125.service.UserFactory {

    @Override
    public User createUser(String name, String password) {
        return new User(name, password);
    }
}

我的问题是我需要通过工厂 class 创建新用户然后保存它但出现此错误:无法调用“com.project.CS4125.service.CustomerFactory.createUser(String, String)”因为“this.userFactory”是 null

任何帮助表示赞赏。

看一下代码的这一部分。 它显示了多少个自动装配字段?

    @Autowired
    private UserService userService;
    private CustomerFactory userFactory;
    private UserController controller;

答案是一个, UserService

@Autowired等注解仅适用于紧随其后的元素。 这部分代码显示了一个带有@Autowired注释的字段和两个没有此注释的字段。 因此,其他两个字段将保留其默认值null ,因此NullPointerException会尝试调用CustomerFactory的方法。

如果您希望自动装配所有这三个字段的值,请确保所有三个字段都具有@Autowired注释:

    @Autowired
    private UserService userService;

    @Autowired
    private CustomerFactory userFactory;

    @Autowired
    private UserController controller;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM