Spring Servlet项目中JpaRepository注入出现NullPointerException问题求助
这个NullPointerException问题非常典型,本质是Spring没有帮你注入UserRepository实例,根源在于你的UserService要么没被Spring容器管理,要么你在Servlet里是手动new出来的,导致Spring的依赖注入机制完全没生效。下面是一步步的解决方案:
1. 给UserService添加@Service注解
首先,你的UserService类必须被Spring识别为可管理的Bean,一定要加上@Service注解:
@Service public class UserService { @Autowired private UserRepository userRepository; public void saveUser(User user) { userRepository.save(user); } }
如果没有这个注解,Spring根本不会创建UserService的实例,更别说自动注入UserRepository了。
2. 不要在Servlet中手动new UserService
你在ExplorerServlet里大概率是直接通过new UserService()来调用方法的——这种方式创建的对象不在Spring容器的管控范围内,里面的@Autowired自然不会生效,userRepository就会是null。
正确的做法是在Servlet的init()方法中,从Spring Web上下文获取UserService实例:
public class ExplorerServlet extends HttpServlet { private UserService userService; @Override public void init() throws ServletException { // 从Spring容器中获取UserService的Bean实例 WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); userService = context.getBean(UserService.class); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 处理请求参数,构建User对象 String login = req.getParameter("login"); String password = req.getParameter("password"); User user = new User(login, password); // 使用Spring容器管理的userService调用方法 userService.saveUser(user); // 后续的响应逻辑... } }
3. 检查Spring组件扫描范围
确保你的Spring Boot主启动类(带有@SpringBootApplication注解的类)所在的包是所有业务类的父包。比如主启动类在com.example.testservletjsp,而你的UserService在com.example.testservletjsp.account、UserRepository在com.example.testservletjsp.repository,Spring会自动扫描这些子包。如果你的类在主包之外,需要在主启动类上添加@ComponentScan(basePackages = {"你的目标包路径"})来指定扫描范围。
4. 清理pom.xml中的冲突依赖
看你的pom.xml里单独引入了spring-context 5.2.8.RELEASE,但Spring Boot 2.7.3版本对应的Spring框架版本是5.3.22,这个单独的依赖会导致版本冲突,建议删掉这部分:
<!-- 移除这个冲突依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.8.RELEASE</version> </dependency>
spring-boot-starter-web已经包含了spring-context的相关依赖,不需要单独引入。
完成以上步骤后,重启应用,Spring会自动创建UserService和UserRepository的实例并完成依赖注入,调用save方法时就不会再出现NullPointerException了。
内容的提问来源于stack exchange,提问作者Murrchalkina

