gpt4 book ai didi

java - 我如何才能限定我不使用的 Autowiring 器 "own"

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:19:35 29 4
gpt4 key购买 nike

要点是 Spring Batch (v2) 测试框架具有带有 @Autowired 注释的 JobLauncherTestUtils.setJob。我们的测试套件有多个 Job 类提供者。因为这个类不是我可以修改的东西,所以我不确定我如何才能限定它 Autowiring 的作业,这可能因测试而异。

 STDOUT [WARN ] [2015.04.15 11:14:42] support.GenericApplicationContext - Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobLauncherTestUtilsForSnapshot': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.batch.test.JobLauncherTestUtils.setJob(org.springframework.batch.core.Job); nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.springframework.batch.core.Job] is defined: expected single matching bean but found 2: coverageRuleBatch,generateMetricsSnapshotJob

我已经尝试添加这个被识别的 JavaConfig,但错误提示它仍在自动调用 setJob

@Configuration
public class SpringTestConfiguration
{
@Bean
public JobLauncherTestUtils jobLauncherTestUtilsForSnapshot( final Job generateMetricsSnapshotJob )
{
JobLauncherTestUtils jobLauncherTestUtils = new JobLauncherTestUtils();
jobLauncherTestUtils.setJob( generateMetricsSnapshotJob );
return jobLauncherTestUtils;
}
}

注意:我不需要 JavaConfig 解决方案,但它会很好。另外,如果可能的话,我希望仍然 Autowiring JobRepository 等字段,因为只有一个。

最佳答案

当我遇到同样的问题时,我的解决方案是限制组件扫描,以便在测试上下文中只创建一个作业 bean。

@Configuration
@ComponentScan(basePackages={
"com.example.batch.jobs.metrics", //package where generateMetricsSnapshotJob is the only job
"com.example.batch.common",
"..."
})
public class SpringTestConfiguration
{
@Bean
public JobLauncherTestUtils jobLauncherTestUtils()
{
//generateMetricsSnapshotJob and other requirements will be autowired
return new JobLauncherTestUtils();
}
}

您可能需要调整您的包结构才能使其正常工作。

关于java - 我如何才能限定我不使用的 Autowiring 器 "own",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29655796/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com