You need to enable JavaScript to run this app. Spring-Cucumber验收测试中@Autowire注入失败问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Spring-Cucumber验收测试中@Autowire注入失败问题求助

Cucumber与Spring集成配置问题排查

问题根源

你碰到的org.springframework.beans.factory.NoSuchBeanDefinitionException,核心原因是Spring容器无法找到MyClass类型的可注入Bean,结合你的模块结构和现有配置,问题出在Spring上下文的Bean扫描范围、Cucumber的配置逻辑上。

配置修正方案

1. 调整Spring上下文配置类(SpringIntegrationTest.java)

SpringIntegrationTest是Cucumber用来加载Spring上下文的核心类,必须确保它能扫描到业务模块的Bean:

@SpringBootTest
// 指定业务模块的包路径,让Spring扫描到Service层的Bean
@ComponentScan(basePackages = "com.asite.iotgateway.cucumberspringboot.service")
@CucumberContextConfiguration
public class SpringIntegrationTest {
}

如果业务模块本身有@SpringBootApplication或@Configuration类,也可以直接通过@SpringBootTest(classes = 业务模块配置类.class)来复用已有配置,避免重复扫描配置。

2. 简化Cucumber启动类(CucumberIntegrationTest.java)

  • 移除多余的@SpringBootConfiguration注解,Cucumber会通过SpringIntegrationTest加载Spring上下文,无需在此类重复配置;
  • glue参数只需要指定Cucumber步骤定义所在的包,业务模块包不需要在这里配置,Spring上下文会负责加载这些Bean:
@Cucumber
@CucumberOptions(features = "classpath:feature/",
                 glue = "com.asite.iotgateway.cucumberspringboot.cucumberGlue")
public class CucumberIntegrationTest {
}

3. 关于@SpringBootApplication的必要性

验收测试模块不需要单独编写带有@SpringBootApplication的Application.java文件,只要保证Spring上下文能扫描到业务模块的Bean即可。除了上面提到的@ComponentScan,也可以直接引用业务模块中已有的@SpringBootApplication类,让测试复用业务模块的上下文配置。

额外检查点

  • 确认验收测试模块已正确依赖业务模块(Service模块),编译和运行时能访问到MyClass的类文件;
  • 检查MyClass上是否添加了Spring的管理注解(比如@Service、@Component、@Repository等),只有被Spring标记为Bean的类才能被@Autowired注入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 07:45:48