【发布时间】:2016-05-04 00:43:25
【问题描述】:
我在不同的包中有以下类:
@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) 指定我想要启用的功能。 )
【问题讨论】:
-
您还知道,当您自己指定
@Enable*时,会禁用 Spring Boot 自动配置您的应用程序的某些部分...导致这类问题。 -
我明白这一点。当我的单元测试似乎“继承”@EnableAutoConfiguration 时,我选择了那条路。当我想要一个单元测试来仅测试 Batch/JMS 代码但正在获取 Web/Servlet 代码(和问题)时,这会导致问题。所以我尝试将配置分开,并从需要它们的单元测试中引用这些类。
-
此外,Spring Boot 已经启用了 web mvc,而无需添加该类,它不会添加任何内容(但禁用了默认的 Spring Boot 配置)。
-
好的,所有@Enable* 都消失了,除了来自@SpringBootApplication 的隐式@EnableAutoConfiguration。但我又回到了 ScheduleJob 课程中得到
No qualifying bean of type [org.springframework.batch.core.configuration.annotation.JobBuilderFactory]。我想这发生在几个小时前,这就是我开始走这条路的原因...... :( -
您是否在测试类中使用了正确的注释?使用
@ContextConfiguration是行不通的。
标签: java spring-boot spring-batch spring-annotations spring-boot-actuator