0

我在不同的包中有以下类:

@EnableWebMvc
public class ActuatorConfig
{
    // empty
    // only needed to get REST so I can hit Actuator endpoints
}

@Component // REMOVE THIS LINE?
@EnableBatchProcessing
public class BatchConfig
{
    // empty
}

@Component
@Configuration
public class ScheduleJob
{
    @Autowired
    private JobBuilderFactory jobBuilder;

    @Bean
    protected JobExecutionListener scheduleJobListener()
    {
        return new ScheduleJobListener();
    }
}

(编辑:添加应用程序类)

@SpringBootApplication
public class AfxApplication
{
    public static void main(String[] args)
    {
        SpringApplication.run(AfxApplication.class, args);
    }
}

第一类打开执行器功能。我不需要任何其他注释。

但是,如果我如上所述从 BatchConfig 中删除 @Component,Boot 将无法启动,因为它找不到填充 @Autowired ScheduleJob.jobBuilder 所需的对 JobBuilderFactory 的依赖项。

例外:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.batch.core.configuration.annotation.JobBuilderFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
... 25 common frames omitted

什么时候需要@Component,什么时候不需要?

(我删除了@Enable* 注释,因为我正在尝试运行不需要启用所有功能的单元测试,这样我可以使用@ComponentScan(basePackageClasses) 指定我想要启用的功能。)

4

1 回答 1

0

感谢 M. Deinum,我终于有了答案。

通过拥有@Enable*,我正在禁用@EnableAutoConfiguration。唯一的例外是@EnableBatchProcessing,这是明确要求的。(我明白是这样,但我不知道为什么它不能被处理@EnableAutoConfiguration。)

答案是上面列出的 Application 类和这个类的组合:

@Configuration
@EnableBatchProcessing
public class BatchConfig
{
}

一旦这到位,其他一切工作。

这将如何影响我的测试代码将是另一天的任务......

于 2016-01-27T08:59:24.780 回答