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

调用@Autowired注入的car类时触发java.lang.NullPointerException问题

问题分析

你的代码触发java.lang.NullPointerException,核心原因有两个:

  1. Tyre类未被Spring容器管理——Spring仅会对标注@Component(或@Service、@Controller等衍生注解)的类创建实例并完成依赖注入,普通类不会触发自动注入逻辑。
  2. 测试方法未启动Spring上下文——直接执行普通@Test时,Spring容器未初始化,cars变量自然不会被注入。
解决方案

步骤1:将Tyre纳入Spring容器管理

给Tyre类添加@Component注解,让Spring识别并创建它的实例:

@Component
public class Tyre  {
    @Autowired
    private car cars;

    void print(){
        cars.getCar();
    }
}

步骤2:用Spring测试框架运行测试

如果是单元测试,需要通过Spring测试注解启动上下文,确保依赖注入生效。修改测试类如下:

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

// Spring Boot项目用@SpringBootTest启动上下文
@SpringBootTest
public class TyreTest {
    @Autowired
    private Tyre tyre;

    @Test
    void printCar() {
        tyre.print();
    }
}

补充提示

  • 遵循Java编码规范:建议把类名car改为Car(大驼峰命名)。
  • 非Spring Boot项目:需在测试类上用@ContextConfiguration指定配置类/XML配置,手动加载Spring上下文。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 09:15:41