如何在代码中获取Spring applciation启动时间

时间:2016-12-29 19:10:27

标签: spring spring-boot

当我启动Spring应用程序时,我可以在控制台中看到启动时间(我正在使用IntelliJ IDEA)。

例如,下面的日志显示应用程序的启动时间为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端点打印出应用程序启动时间。

3 个答案:

答案 0 :(得分:1)

这个答案是基于Sotirios的评论。

首先,创建一个实现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

答案 1 :(得分: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());
}
....

您可以使用Spring实用程序 StopWatch (org.springframework.util.StopWatch)获取应用程序启动时间

答案 2 :(得分:0)

使用ApplicationReadyEvent可以减少干扰并减少更改。

@SpringBootApplication
public class TrackSpringBootTimeApp {
    private static Instant startTime;
    private static Instant endTime;

    public static void main(String[] args) {
        startTime = Instant.now();
        SpringApplication.run(TrackSpringBootTimeApp.class);
        System.out.println("Total time taken in start up " + 
        Duration.between(startTime, endTime).toString());
    }

    @EventListener(ApplicationReadyEvent.class)
    public void startApp() {
        endTime = Instant.now();
    }
}