如何限定我不“拥有”的自动装配器? [英] How can I qualify an autowired setter that I don't "own"

查看:214
本文介绍了如何限定我不“拥有”的自动装配器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要点是Spring Batch(v2)测试框架的 JobLauncherTestUtils.setJob 带有 @Autowired 注释。我们的测试套件有多个 Job 类提供程序。由于这个课程不是我可以修改的课程,我不确定如何确定自动配对的工作,每个测试可能会有所不同。

The gist is that the Spring Batch (v2) test framework has JobLauncherTestUtils.setJob with an @Autowired annotation. Our test suite has multiple Job class providers. Since this class is not something I can modify, I'm not sure how I can qualify which job it gets autowired with, which may be different per test.

 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

I've tried adding this JavaConfig which is recognized, but the error says it's still autocalling setJob

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

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

note: I don't require a JavaConfig solution, but it'd be nice. Also, I'd like, if possible, to still Autowire fields like JobRepository, as there is only one.

推荐答案

解决方案我想出了

@Configuration
public class SpringBatchTestConfiguration
{
@Bean
public static JobLauncherTestUtils jobLauncherTestUtilsForSnapshot()
{
    return new SnapshotJobLauncherTestUtils();
}

public static class SnapshotJobLauncherTestUtils extends JobLauncherTestUtils
{
    @Override
    @Qualifier( "generateMetricsSnapshotJob" )
    public void setJob( final Job job )
    {
        super.setJob( job );
    }
}
}

和最终测试

@Autowired
@Qualifier( "jobLauncherTestUtilsForSnapshot" )
protected JobLauncherTestUtils jobLauncherTestUtils;

相当自信我可以用@Component注释我的TestUtils并正确命名并做同样的事情。

fairly confident I could just annotate my TestUtils with @Component and name it properly and do the same thing.

这篇关于如何限定我不“拥有”的自动装配器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆