Skip to main content

ApplicationStartingEvent and ApplicationEnvironmentPreparedEvent code example

Both ApplicationStartingEvent and ApplicationEnvironmentPreparedEvent are executed before the application start and may be useful to modify or read the application or environment at runtime such as profiles.

SpringBootTutorialApplication.java

@SpringBootApplication
public class SpringBootTutorialApplication implements AsyncConfigurer{

 public static void main(String[] args) {
  SpringApplication app = new SpringApplication(SpringBootTutorialApplication.class);
  
  //register ApplicationEnvironmentPreparedEvent
  app.addListeners((ApplicationEnvironmentPreparedEvent event)->{
   System.out.println("Executing ApplicationEnvironmentPreparedEvent...");
  });
  //register ApplicationStartingEvent
  app.addListeners((ApplicationStartingEvent event)->{
   System.out.println("Executing ApplicationStartingEvent...");
  });

  //start the application
  app.run(args);
 }
}

Output

Below output shows that both the events are executed before application start.
Executing ApplicationStartingEvent...
Executing ApplicationEnvironmentPreparedEvent...

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.9.RELEASE)

Comments

Post a Comment