13
17

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.

@SpringBootApplication利用上の注意

Last updated at Posted at 2015-11-11

前回、RabbitMQの実装をしていて気づいたのですが、
@SpringBootApplicationアノテーションを付与したmainメソッドを持つクラスを1つのProjectに2つ用意した場合に同時に動くという事がわかりました。
知らないで利用しているとちゃんと動いているのか不安になるのですが、知っていればフロントエンドとバックエンドを一つのインスタンスでまかなえるという事に気づいたりします。

STSではメインメソッドが複数ある場合に下記のように選択でき、build.gradleでも起動時のメインメソッドを指定できるので、サンプル用に1つのプロジェクト内に沢山のメインメソッドを入れていました。
スクリーンショット 2015-11-09 23.57.29.png

こっちがもともとあるフロント用のクラスです。
@SpringBootApplication
@Configuration,@EnableAutoConfiguration,@ComponentScanを呼び出します。
@ComponentScan@Componentを全部使えるようにしてくれるので、@Componentを含む@Controllerが有効になります。

SpringDemoApplication.java
package demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class SpringDemoApplication {

public static void main(String[] args) {

        SpringApplication application = new SpringApplication(SpringDemoApplication.class);
        ApplicationContext context = application.run(args);

    }
}

あとから、バックグラウンド用の処理に追加したクラス。
タイマーなどを組み合わせるとより正確に定期実行のタスクを簡単にプロジェクト内に組み込む事ができます。
ウェブの機能が入っているのと同じJARファイル内で動いています。

@Component

BackgroundTasks.java
package demo;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class BackgroundTasks implements CommandLineRunner {

	@Autowired
	ApplicationContext context;
	
    public static void main(String[] args) throws InterruptedException {
        SpringApplication.run(RabbitMQApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("Waiting five seconds...");
       
        while(0 < 1){
        	for(int i = 0 ; i < 5 ; i++){
        		System.out.println(new Date().toGMTString() + ": " + String.valueOf(i));
        	}
        	Thread.sleep(10000);
        }
    }
}

訂正
@SpringBootApplicationではなく、
@ComponentとCommandLineRunnerが実装されている場合に、同じインスタンス内で起動してるみたいです。

13
17
2

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
13
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?