LoginSignup
5
3

More than 3 years have passed since last update.

spring-batchで複数DataSource定義時に使用する@BatchDataSource

Posted at

spring-batchで複数のDataSourceを定義する場合、@BatchDataSourceでspring-batchのauto-configurationで使用する方を指定できる。@BatchDataSourceのjavadocによると2.2.0で追加されたものらしい。

その定義は以下のようになっており、実態は単なる@Qualifier。javadocによると典型的な使い方としては、@Primaryを付与するメインのDataSourceと、このアノテーションを付与するspring-batch用のセカンドDataSource、というもの。メインとなるDBと、メタデータ格納先DBが分かれてる場合にこれを使う、といった感じだろう。

/**
 * Qualifier annotation for a DataSource to be injected into Batch auto-configuration. Can
 * be used on a secondary data source, if there is another one marked as
 * {@link Primary @Primary}.
 *
 * @author Dmytro Nosan
 * @since 2.2.0
 */
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Qualifier
public @interface BatchDataSource {

}

使用例。

    @Bean
    @BatchDataSource
    public DataSource springBatchDs() {
        return DataSourceBuilder.create().url("jdbc:h2:~/test").username("sa").password("").build();
    }

    @Bean
    @Primary
    public DataSource primaryDs() {
        return DataSourceBuilder.create().url("jdbc:oracle:thin:system/oracle@localhost:11521/XEPDB1").username("system").password("oracle").build();
    }

上記の例の場合、メインはOracle、メタデータ格納先をH2、としている。

従来もこういう設定が出来なかったわけではないが、専用アノテーションにより意図が明示しやすくなる、と思われる。

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3