11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Spring Batch 動かしてみた

11
Posted at

経緯

先日これ に行って楽しかったので、なんとなく前から気になっていた Spring Batch を触ってみた。
Spring Boot がなんなのかはいまだによくわかっていない。

手順

基本的には公式のガイドに従ったけど、以下の点を変えた。コレが原因で若干ハマった。

  • mainクラスとバッチ処理のクラスをは別パッケージにした。

通常 main があるところとバッチ処理をするクラスのパッケージは分けたい気がしたので。

問題

最初下記のような構成にした。

.
├── batch
│   └── BatchConfiguration.java
└── hello
    ├── Application.java (main)
    ├── Person.java
    └── PersonItemProcessor.java

これでなんとかビルドは通ったものの、肝心のバッチ処理がキックされていない様子。
上記ガイドを良く読むと、どうも@ComponentScanをつけたクラスと同じパッケージ下に@Configuration をつけたバッチの定義クラスがないと動かないらしかった。@Comfiguration@Componentの一種らしい。(参照
つまり、Application.java とBatchConfiguration.java は同じパッケージにないとだめっぽい。

以下の構成にしたら、バッチ処理が動いた。

.
├── batch
│   ├── Application.java
│   └── BatchConfiguration.java
└── hello
    ├── Person.java
    └── PersonItemProcessor.java

所感

Application.java のmain関数は以下の通り。
ResultSet の処理はラムダで書き直してみた。

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);

        List<Person> results = 
            ctx.getBean(JdbcTemplate.class)
                .query("SELECT first_name, last_name FROM people",
                    (ResultSet rs, int row) -> {
                        return new Person(rs.getString(1), rs.getString(2));
                    }   
                );  

        System.out.println(results.size() + " Persons was found.");
        for (Person person : results) {
            System.out.println("Found <" + person + "> in the database.");
        }   
    }

Batch という文字がどこにも出てこないので、全然バッチをキックしてるように見えない。使いこなすまでは自分でもなにやってるかわからなくなりそうだなー。

一応ソースはこちら。
https://github.com/toshi0383/spring-test

おわり

11
11
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
11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?