问题描述
我正在尝试在Spring Batch中配置几个数据源。在启动时,Spring Batch抛出以下异常:
I am trying to configure a couple of datasources within Spring Batch. On startup, Spring Batch is throwing the following exception:
要使用默认的BatchConfigurer,上下文必须包含不多于一个DataSource,找到2
批量配置的片段
Snippet from Batch Configuration
@Configuration
@EnableBatchProcessing
public class BatchJobConfiguration {
@Primary
@Bean(name = "baseDatasource")
public DataSource dataSource() {
// first datasource definition here
}
@Bean(name = "secondaryDataSource")
public DataSource dataSource2() {
// second datasource definition here
}
...
}
不确定为什么我会看到这个异常,因为我已经看到一些基于xml的Spring批处理配置声明了多个数据源。我使用Spring Batch核心版本3.0.1.RELEASE与Spring Boot版本1.1.5.RELEASE。任何帮助将不胜感激。
Not sure why I am seeing this exception, because I have seen some xml based configuration for Spring batch that declare multiple datasources. I am using Spring Batch core version 3.0.1.RELEASE with Spring Boot version 1.1.5.RELEASE. Any help would be greatly appreciated.
推荐答案
尝试查找,如果没有找到,则尝试自己创建它 - 这是 IllegalStateException
在多个 DataSource
容器中的bean。
AbstractBatchConfiguration
tries to lookup BatchConfigurer
in container first, if it is not found then tries to create it itself - this is where IllegalStateException
is thrown where there is more than one DataSource
bean in container.
解决问题的方法是防止创建 bean AbstractBatchConfiguration
。
要做到这一点,我们提示使用注释:
The approach to solving the problem is to prevent from creation the DefaultBatchConfigurer
bean in AbstractBatchConfiguration
.To do it we hint to create DefaultBatchConfigurer
by Spring container using @Component
annotation:
配置类,其中我们可以使用扫描包含空类的包派生自 DefaultBatchConfigurer
:
package batch_config;
...
@EnableBatchProcessing
@ComponentScan(basePackageClasses = MyBatchConfigurer.class)
public class MyBatchConfig {
...
}
该空派生类的完整代码在此处:
the full code of that empty derived class is here:
package batch_config.components;
import org.springframework.batch.core.configuration.annotation.DefaultBatchConfigurer;
import org.springframework.stereotype.Component;
@Component
public class MyBatchConfigurer extends DefaultBatchConfigurer {
}
在此配置中,注释适用于 DataSource
bean,如下例所示:
In this configuration the @Primary
annotation works for DataSource
bean as in the example below:
@Configuration
public class BatchTestDatabaseConfig {
@Bean
@Primary
public DataSource dataSource()
{
return .........;
}
}
这适用于Spring Batch版本3.0.3.RELEASE
This works for the Spring Batch version 3.0.3.RELEASE
最简单的解决方案 @Primary
DataSource 上的注释工作可能只是添加 @ComponentScan(basePackageClasses = DefaultBatchConfigurer.class)
以及 @EnableBatchProcessing
注释:
The simplest solution to make @Primary
annotation on DataSource
work might be just adding @ComponentScan(basePackageClasses = DefaultBatchConfigurer.class)
along with @EnableBatchProcessing
annotation:
@Configuration
@EnableBatchProcessing
@ComponentScan(basePackageClasses = DefaultBatchConfigurer.class)
public class MyBatchConfig {
这篇关于在Spring Batch中使用多个DataSource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!