提问者:小点点

Spring JavaConfig-在@Bean注释的配置方法上禁用自动装配


我正在尝试将一些现有的基于xml的配置转换为JavaConfig,但我遇到了困难。

@Configuration
@Import(TestContext.class)
public class BatchUsageReportJobTestContext {

    @Bean(name = "test.jobLauncher")
    public JobLauncherTestUtils jobLauncher(@Qualifier("reporting.job.usageReportJob") Job job, // From TestContext.class
                                            @Qualifier("test.simpleJobLauncher") JobLauncher jobLauncher) { // From TestContext.class
        JobLauncherTestUtils jobLauncherTestUtils = new JobLauncherTestUtils();
        jobLauncherTestUtils.setJob(job);
        jobLauncherTestUtils.setJobLauncher(jobLauncher);

        return jobLauncherTestUtils;
    }
}

JobLauncherTestUtils是一段Spring批处理代码:

public class JobLauncherTestUtils {
  private Job job;

  @Autowired
  public Job setJob(Job job) {
    this.job = job;
  }
}

问题是,在调用了我的@Bean方法,并且使用正确的@Qualifer注释bean调用了setter之后,Spring尝试在它可以找到的字段中@Autowire(不是@Qualified),覆盖了我设置的字段。问题是Job类型的bean不止一个,所以我得到了以下结果:

... 42 more
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.springframework.batch.core.Job] is defined: expected single matching bean but found 3: reporting.job.reportProcessing,reporting.job.summaryReport,reporting.job.usageReportJob
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1126)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:618)
... 44 more

我不认为这里最好做什么。通过XML配置,你可以拥有任意类型的bean,并挑选合适的一个——这似乎是不可能的,或者至少不容易实现。我做错了什么?理想情况下,我希望@Bean注释类只注册一个bean——不做任何魔法。设置autowire=Autowire.NO也没有帮助。


共1个答案

匿名用户

一般我们在声明上方或getters上方使用注释。所以试试这个:

public class JobLauncherTestUtils {

  @Autowired
  private Job job;

  public Job setJob(Job job) {
    this.job = job;
  }
}