2017-06-11 4 views
0

私はいくつかのコマンド(タスク)を実行するはずのスプリングクラウドタスクを持つスプリングブートアプリケーションを作成しました。 各タスク/コマンドは短命のタスクであり、すべてのタスクはコマンドラインから開始し、短いETLジョブを実行して実行を終了します。複数のスプリングブートコマンドライン引数に基づくCommandLineRunner

すべてのコマンド/タスクを含むスプリングブートジャーが1つあります。 各タスクはCommandLineRunnerであり、コマンドラインからのparamsに基づいて実行されるタスク(1つ以上)を決定するのが好きです。 そうするベストプラクティスは何ですか? 「else else」などと尋ねる汚れたコードは好きではありません。

+0

CommandLineRunner実装ngleアプリケーション・コンテキストのホールドを取得し、名前で必要なBeanを解決し、私の例は、単に最初の引数を使用し、それはMyCommandLineRunner.run()メソッドの呼びかけ'java -jar myapp.jar'ではなく' java -classpath myapp.jar com.example.Task1'をコマンドラインで実行することができます。 if-elseはどこにも見えません。しかし、なぜ、他の人にとって嫌なのか?プログラムは何度かに分岐します。 – Barend

+0

ありがとう、私は春のブートが複数のメインクラスを使用することを許可しているか分からない。ハードコーディングされたif-elseを使用することは、メンテナンスが難しく、コンポーネントを挿入する – Shay

答えて

1

Springブートは、アプリケーションコンテキストからすべてCommandLineRunnerまたはApplicationRunnerのBeanを実行します。任意の引数で1つを選択することはできません。あなたが異なるCommandLineRunner実装を持っており、それぞれにあなたがこの特別なCommandLineRunnerが実行する必要があるかどうかを決定するために引数をチェック

  1. だから基本的には次の2つのpossibiitiesを持っています。

  2. ディスパッチャとして機能するのは1つだけCommandLineRunnerです。コードは次のようになります:

これはあなたのランナーが実装する新しいインタフェースです:

public interface MyCommandLineRunner { 
    void run(String... strings) throws Exception; 
} 

あなたは、その後の実装を定義し、名前でそれらを識別:

@Component("one") 
public class MyCommandLineRunnerOne implements MyCommandLineRunner { 
    private static final Logger log = LoggerFactory.getLogger(MyCommandLineRunnerOne.class); 

    @Override 
    public void run(String... strings) throws Exception { 
     log.info("running"); 
    } 
} 

@Component("two") 
public class MyCommandLineRunnerTwo implements MyCommandLineRunner { 
    private static final Logger log = LoggerFactory.getLogger(MyCommandLineRunnerTwo.class); 
    @Override 
    public void run(String... strings) throws Exception { 
     log.info("running"); 
    } 
} 

そして、あなたはjarファイル内に複数の主なクラスを持っている場合は

@Component 
public class CommandLineRunnerImpl implements CommandLineRunner, ApplicationContextAware { 
    private ApplicationContext applicationContext; 


    @Override 
    public void run(String... strings) throws Exception { 
     if (strings.length < 1) { 
      throw new IllegalArgumentException("no args given"); 
     } 

     String name = strings[0]; 
     final MyCommandLineRunner myCommandLineRunner = applicationContext.getBean(name, MyCommandLineRunner.class); 
     myCommandLineRunner.run(strings); 
    } 

    @Override 
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 
     this.applicationContext = applicationContext; 
    } 
} 
+0

私たちはspring cliのコマンドCliCommandアノテーションで実装しようとしています。 それぞれのコマンドは、コマンドライン – Shay

+0

の引数をすでに解析している "メイン"のようですが、これはSpring Boot CommandLine Runnerとは異なるものです。申し訳ありません、それを使用したことはありません –

関連する問題