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

Spring框架Autowired Bean注入NullPointerException问题排查求助

解决Spring TestNG测试中@Autowired出现NullPointerException的问题

你遇到的核心问题是:TestNG测试类里的@Autowired Bean没有被正确注入,导致空指针异常。虽然你已经配置了@ContextConfiguration,但TestNG本身不会自动触发Spring容器的初始化和依赖注入逻辑——必须集成Spring TestContext框架,才能让注解生效。

问题根源

你的测试类仅添加了@ContextConfiguration注解,但没有接入Spring为TestNG提供的测试支持类/监听器,导致Spring无法接管测试类的生命周期,自然不会注入helloWorldService实例。而你手动创建ClassPathXmlApplicationContext能拿到Bean,是因为那是你主动初始化了Spring容器,但这和@Autowired的自动注入逻辑完全独立。

解决方案

最简单的修复方式是让测试类继承AbstractTestNGSpringContextTests,这个类已经封装了Spring上下文加载、依赖注入、测试生命周期管理等核心逻辑。

步骤1:确保依赖包含spring-test

如果用Maven,确认pom.xml中存在:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>你的Spring版本(比如3.0.x)</version>
    <scope>test</scope>
</dependency>

Gradle项目则添加:

testImplementation 'org.springframework:spring-test:你的Spring版本'

步骤2:修改测试类代码

让测试类继承AbstractTestNGSpringContextTests:

import cz.aegis.watchdog.api.model.HelloWorldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.Assert;
import org.testng.annotations.Test;

@ContextConfiguration(locations = {"classpath:appCtx-watchdog-test-server.xml"})
public class Testing extends AbstractTestNGSpringContextTests { // 继承Spring TestNG基础类
    @Autowired
    private HelloWorldService helloWorldService;

    @Test
    public void autowiredServiceTest() {
        System.out.println(helloWorldService.getString());
        Assert.assertTrue(helloWorldService.getTrue());
    }
}

额外说明

  • AbstractTestNGSpringContextTests会自动帮你完成:启动Spring上下文、注入@Autowired标记的Bean、测试完成后清理上下文等操作。
  • 如果你不想继承类,也可以通过添加@TestExecutionListeners(DependencyInjectionTestExecutionListener.class)注解来实现依赖注入,但继承基础类是最简洁的方案。
  • 从你的配置来看,context:component-scan的base-package已经覆盖了HelloWorldServiceImpl所在的包,这部分无需调整。

修改后,TestNG运行测试时会先初始化Spring容器,自动注入helloWorldService,空指针问题就能解决了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:31:46