LoginSignup
45
43

More than 5 years have passed since last update.

Spring Boot でコマンドラインアプリケーションを作成する

Posted at

コマンドライン引数を指定して起動するようなアプリをSpring Bootで作成する場合は CommandLineRunner を使います。

@EnableAutoConfiguration
@ComponentScan
public class Application implements CommandLineRunner {

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

    @Override
    public void run(String... args) {
        // Do something...
    }
}

Spring Boot Reference Guide 20.6 Using the CommandLineRunner でも書かれているように CommandLineRunner を実装したクラスに @Component を付与しておけば、コンポーネントスキャンで拾って勝手に実行してくれます。

また、 CommandLineRunner 実装クラスが複数ある場合、org.springframework.core.Ordered インターフェースや org.springframework.core.annotation.Order アノテーションを使うと実行順序を指定することができます。

Application.java
@EnableAutoConfiguration
@ComponentScan
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
DefaultCommandLineRunner.java
public class DefaultCommandLineRunner implements CommandLineRunner {
    public void run(String... args) throws Exception {
        System.out.println(Arrays.asList(args).stream().collect(Collectors.joining(",", getClass().getSimpleName() + "[", "]")));
    }
}
Runner1.java
@Component
@Order(3)
public class Runner1 extends DefaultCommandLineRunner {}
Runner2.java
@Component
@Order(2)
public class Runner2 extends DefaultCommandLineRunner {}
Runner3.java
@Component
@Order(1)
public class Runner3 extends DefaultCommandLineRunner {}
$ java -jar build/libs/ordered-command-line-runner-examples-1.0.0.jar hoge moge hage

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.1.8.RELEASE)


Runner3[hoge,moge,hage]
Runner2[hoge,moge,hage]
Runner1[hoge,moge,hage]

ちなみに、順序を指定しなくてもエラーにはなりません。
どんな局面で使うのか分かりませんが・・・。

45
43
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
45
43