Springブートは、アプリケーションコンテキストからすべてCommandLineRunner
またはApplicationRunner
のBeanを実行します。任意の引数で1つを選択することはできません。あなたが異なるCommandLineRunner
実装を持っており、それぞれにあなたがこの特別なCommandLineRunner
が実行する必要があるかどうかを決定するために引数をチェック
- :
だから基本的には次の2つのpossibiitiesを持っています。
- ディスパッチャとして機能するのは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;
}
}
:
CommandLineRunner
実装ngleアプリケーション・コンテキストのホールドを取得し、名前で必要なBeanを解決し、私の例は、単に最初の引数を使用し、それはMyCommandLineRunner.run()
メソッドの呼びかけ'java -jar myapp.jar'ではなく' java -classpath myapp.jar com.example.Task1'をコマンドラインで実行することができます。 if-elseはどこにも見えません。しかし、なぜ、他の人にとって嫌なのか?プログラムは何度かに分岐します。 – Barendありがとう、私は春のブートが複数のメインクラスを使用することを許可しているか分からない。ハードコーディングされたif-elseを使用することは、メンテナンスが難しく、コンポーネントを挿入する – Shay