You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring中调用CustomerFactory因对象为空报错的解决求助

解决方案:Cannot invoke "CustomerFactory.createUser(...) because this.userFactory is null

核心问题分析

报错的根源是userFactory对象未被Spring容器初始化注入,存在两个关键问题:

  • CustomerFactory类没有被Spring识别为可管理的Bean,Spring无法为其创建实例
  • IndexController中的userFactory字段缺少注入注解,Spring无法自动装配该对象

步骤1:将CustomerFactory纳入Spring管理

给CustomerFactory添加@Component(或@Service)注解,让Spring扫描并创建该类的实例:

import org.springframework.stereotype.Component;

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

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

步骤2:在IndexController中注入userFactory

有两种注入方式可选,推荐使用构造注入(Spring官方规范,避免空指针并提升可测试性):

方式1:字段注入(快速修复)

@Controller
public class IndexController {

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

    // 剩余代码保持不变...
}

方式2:构造注入(更规范)

@Controller
public class IndexController {

    private final UserService userService;
    private final CustomerFactory userFactory;
    private final UserController controller;

    @Autowired
    public IndexController(UserService userService, CustomerFactory userFactory, UserController controller) {
        this.userService = userService;
        this.userFactory = userFactory;
        this.controller = controller;
    }

    // 剩余代码保持不变...
}

额外检查项

  • 确保Spring Boot主启动类所在包是所有业务类的父包,或通过@ComponentScan指定扫描范围,保证CustomerFactory和IndexController能被Spring扫描到
  • 若使用Spring Boot,主启动类的@SpringBootApplication注解默认会扫描其所在包及子包下的类

可选优化:修复Thymeleaf表单绑定问题

当前注册页面的input未使用Thymeleaf的th:field属性,可能导致@ModelAttribute User user无法正确接收表单数据,建议修改表单:

<form action="#" th:action="@{/register}" th:object="${user}" method="post">
  <p>User Name <input type="text" th:field="*{name}"></p>
  <p>Password <input type="password" th:field="*{password}"></p>
  <button type="submit">Register</button>
</form>

同时在registerForm方法中往Model添加空的User对象:

@GetMapping("/")
public String registerForm(Model model){
    model.addAttribute("user", new User());
    return "index";
}

内容的提问来源于stack exchange,提问作者Collander

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 18:45:47