LoginSignup
6
5

More than 5 years have passed since last update.

SpringBootでEmbeddedWebContainerを起動させない

Last updated at Posted at 2015-04-05

もともとSpringBootでWebアプリとして実装していたものに、一部Serviceクラスやモデルクラスを流用したバッチ処理を加えたい時、バッチ用のMainクラスを以下のように作成しても、内蔵のWebコンテナが起動してしまいます。

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

これは、SpringApplicationクラスの初期化コードに、クラスパス上にjavax.servlet.Servletもしくはorg.springframework.web.context.ConfigurableWebApplicationContextがあるかどうかを確認して、webEnvironmentというboolean変数にtrueを入れてしまうからです(このフラグがtrueだと、Webコンテナが動く)

このため、初期化後にフラグをfalseにすることで、Webコンテナが動作しないようにできます。

public static void main(String[] args) throws Exception {
  SpringApplication application = new SpringApplication(BatchMain.class);
  application.setWebEnvironment(false);
  application.run(args);
}
6
5
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
6
5