When I start my Spring application, I can see the startup time in console (I am using IntelliJ IDEA).
For example, below log shows 13.427s startup time for the application.
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)
Is there a way to get this startup time in the code? I want to print out application startup time in Spring /info
endpoint.
When a Spring Boot Application has slow startup, it can be one or more beans and related dependencies taking longer to initialise and slowing down the entire process. Profiling Spring Boot application doesn't often help in diagnosing the startup issues.
Spring boot provides an ApplicationRunner interface with a run() method to be invoked at application startup.
Spring Boot automatically configures your application based on the dependencies you have added to the project by using @EnableAutoConfiguration annotation. For example, if MySQL database is on your classpath, but you have not configured any database connection, then Spring Boot auto-configures an in-memory database.
This answer is based on Sotirios's comment.
First, create a custom class which implements 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();
}
}
Then, add this line to spring.factories
file.
org.springframework.boot.SpringApplicationRunListener=com.example.AppListener
Using ApplicationReadyEvent is less intrusive and minimal change.
@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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With