2016-12-29 22 views
0

Springアプリケーションを起動すると、コンソールで起動時間がわかります(私はIntelliJ IDEAを使用しています)。コードでSpringアプリケーションの起動時間を取得する

たとえば、以下のログでは、アプリケーションの起動時間が13.427秒になっています。

2016-12-29 13:58:05.491  : Starting Application on 8DSXD72 with PID 14120 
2016-12-29 13:58:05.518  : Running with Spring Boot v1.4.1.RELEASE, Spring v4.3.3.RELEASE 
2016-12-29 13:58:05.519  : The following profiles are active: LOCAL 
2016-12-29 13:58:15.537  : JMX is disabled 
.... 
2016-12-29 13:58:17.392  : Started Application in 13.427 seconds (JVM running for 14.71) 

コードでこの起動時間を取得する方法はありますか?私はアプリケーションの起動時間をSpringの/infoエンドポイントに出力したいと思います。

+1

特定のタイマーは使用できません。 'started'にタイマーを開始し、' finished'でタイマーを停止する 'SpringApplicationRunListener'を登録することで、何か_close_を得ることができます。そして、何らかの形でそれをエンドポイントハンドラーに公開します。 –

+0

@SotiriosDelimanolisありがとう。あなたのソリューションはより良いです。私はそれを受け入れることができるように答えを投稿してください。 – NMSL

答えて

1

この回答はソティリオスさんのコメントに基づいています。

まず、SpringApplicationRunListenerを実装するカスタムクラスを作成します。

package com.example; 

public class AppListener implements SpringApplicationRunListener { 
    public static long appStartTime; 
    public static long appFinishTime; 

    //Constructor is required. 
    public AppListener(SpringApplication application, String[] args) { 
    } 

    @Override 
    public void started() { 
     appStartTime = System.currentTimeMillis(); 
    } 

    @Override 
    public void environmentPrepared(ConfigurableEnvironment environment) { 

    } 

    @Override 
    public void contextPrepared(ConfigurableApplicationContext context) { 

    } 

    @Override 
    public void contextLoaded(ConfigurableApplicationContext context) { 

    } 

    @Override 
    public void finished(ConfigurableApplicationContext context, Throwable exception) { 
     appFinishTime = System.currentTimeMillis(); 
    } 
} 

その後、spring.factoriesファイルに次の行を追加します。

org.springframework.boot.SpringApplicationRunListener=com.example.AppListener 
0
@ComponentScan 
@EnableAutoConfiguration 
@ConfigurationProperties 
public class Application implements CommandLineRunner { 

public static void main(String[] args) { 
    StopWatch stopWatch = new StopWatch("App"); 
    stopWatch.start("App Startup"); 
    SpringApplication.run(Application.class); 
    stopWatch.stop(); 
    System.out.println("Seconds = "+stopWatch.getTotalTimeSeconds()); 
    System.out.println(stopWatch.prettyPrint()); 
} 
.... 

あなたは春のユーティリティストップウォッチ(org.springframework.util.StopWatch)を使用して、アプリケーションの起動時間を得ることができます

関連する問題