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

Spring依赖注入失效求助:@Autowired注入对象为空引发空指针

Spring依赖注入失效:@Autowired对象未注入引发NullPointerException

问题表现

调用接口时触发空指针异常:

java.lang.NullPointerException: Cannot invoke "com.myproject.entity.service.IMyEntityService.getAllMyEntities()" because "this.myEntityService" is null

Controller中多个方法均出现该问题;手动创建MyEntityService实例时,其内部的MyEntityRepository同样无法注入,说明Spring容器未完成Bean的扫描与依赖注入。

相关代码片段

MyEntityController

package com.myproject.api.controller;

import com.myproject.entity.model.MyEntity;
import com.myproject.entity.service.IMyEntityService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
import java.util.List;
 
@Controller
@RequestMapping("/api")
public class MyEntityController {

  @Autowired
  IMyEntityService myEntityService;

  @GetMapping("/my-entities")
  @CrossOrigin(origins = "*")
  @ResponseBody
  public List<MyEntity> getAllMyEntities(){
      List<MyEntity> myEntities = myEntityService.listAllMyEntities();
      return myEntities;
  }
}

MyEntityService

@Service
public class MyEntityService implements IMyEntityService {

    @Autowired
    MyEntityRepository myEntityRepository ;

    @Override
    public List<MyEntity> listAllMyEntities() { // 注:原代码返回值类型错误,应为List<MyEntity>而非List<MyEntityService>
        return this.myEntityRepository.findAll();
    }
}

MyEntityRepository

@Repository
public interface MyEntityRepository extends JpaRepository<MyEntity, Long> {
}

已尝试的无效方案

  • 编写静态方法配置Spring并强制扫描包路径
  • 添加@ComponentScan注解指定扫描范围
  • 修改application.properties相关配置

排查与解决建议

  1. 确认启动类的包扫描范围
    Spring Boot启动类(带@SpringBootApplication)默认扫描自身所在包及其子包。若启动类包层级过深(例如在com.myproject.app下,而业务类在com.myproject.api),需在启动类上显式添加:

    @SpringBootApplication
    @ComponentScan(basePackages = {"com.myproject.api", "com.myproject.entity"})
    @EnableJpaRepositories(basePackages = "com.myproject.entity.repository")
    public class Application {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }
    

    确保所有Controller、Service、Repository所在包都被覆盖。

  2. 校验Bean注解的正确性

    • 确认@Controller、@Service、@Repository均来自org.springframework.stereotype包,未错用其他框架注解。
    • 检查IMyEntityService为接口,MyEntityService正确实现该接口,Spring会自动将实现类作为Bean注入依赖处。
  3. 禁止手动实例化Spring管理的Bean
    不要在Controller中通过new MyEntityService()创建实例,此类对象不受Spring容器管理,内部@Autowired无法生效,必须依赖Spring容器注入Bean。

  4. 修复代码语法错误
    原MyEntityService中listAllMyEntities方法返回值类型错误(List<MyEntityService>),应修正为List<MyEntity>,否则会导致编译错误,间接影响Bean初始化。

  5. 检查JPA配置完整性

    • 启动类需添加@EnableJpaRepositories指定Repository所在包,确保Spring生成JPA代理类。
    • 确认application.properties中数据库URL、用户名、密码配置正确,Spring能正常连接数据库,否则Repository Bean无法初始化。
  6. 验证依赖完整性
    确保构建文件(Maven pom.xml/Gradle build.gradle)包含Spring Web、Spring Data JPA的正确依赖,版本与Spring Boot兼容:

    <!-- Maven示例 -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!-- 数据库驱动依赖,如MySQL -->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>
    
  7. 排查循环依赖
    若存在复杂循环依赖,可能导致Bean初始化失败。可开启Spring DEBUG日志(在application.properties中添加logging.level.org.springframework=DEBUG),查看Bean初始化过程中的异常信息。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 01:52:28