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

Spring Boot 3注入@Service时触发BeanInstantiationException问题求助

Spring Boot 3 Bean实例化空指针异常排查

问题场景

添加以下@Service类后,所有测试失败:

FirstService.java

@Service
public class FirstService {

    private final SecondService secondService;
    private final Client client;

    public FirstService(SecondService secondService) {
        this.secondService = secondService;
        this.client = Client.builder().setId(secondService.getId()).build();
    }
}

SecondService.java

@Service
public class SecondService {
       
    private final ThirdService thirdService;
    
    public SecondService(ThirdService thirdService) {
        this.thirdService = thirdService;
    }
    
    public Id getId() {
       return new Id(thirdService.getId().toString());
    }
}

ThirdService.java

@Component
@RequiredArgsConstructor
public class ThirdService {

    public UUID getId() {
       return UUID.randomUUID();
    }
}

报错信息

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [xxx.xxx.xxx.FirstService]: Constructor threw exception
Caused by: java.lang.NullPointerException: Cannot invoke "java.util.UUID.toString()" because the return value of "xxx.xxx.xxx.ThirdService.getId()" is null

原因分析

  1. 测试环境Mock配置缺失:
    此前测试未触发SecondService.getId()方法,因此未暴露Mock问题。添加FirstService后,其构造器直接调用secondService.getId(),进而触发thirdService.getId()。若测试中使用Mock替代ThirdService,且未指定getId()的返回值,Mock框架(如Mockito)会默认返回null,导致空指针。

  2. Lombok与Spring Boot 3兼容性问题:
    ThirdService上的@RequiredArgsConstructor注解因类中无final成员变量,不会生成构造器,Spring将使用默认无参构造器实例化。若Lombok版本低于1.18.24,可能与Spring Boot 3的依赖处理逻辑冲突,导致Bean实例化异常。

解决方案

针对测试场景

  • 补全Mock方法返回值:
    在测试类中为Mock的ThirdService配置getId()的返回值:
    @MockBean
    private ThirdService thirdService;
    
    @BeforeEach
    void setUp() {
        Mockito.when(thirdService.getId()).thenReturn(UUID.randomUUID());
    }
    
  • 使用真实实例:
    若无需MockThirdService,可移除@MockBean,改用@Autowired注入真实Bean实例。

针对应用启动场景(非测试)

  • 升级Lombok版本:
    在pom.xml(Maven)或build.gradle(Gradle)中确保Lombok版本≥1.18.24:
    <!-- Maven -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.30</version>
        <scope>provided</scope>
    </dependency>
    
  • 移除冗余注解:
    由于ThirdService无final成员变量,@RequiredArgsConstructor注解无实际作用,可直接移除,避免潜在冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 20:04:55