Skip to content

Lab 3: Run on Application Startup


  • Learn about how to run code at startup with the CommandLineRunner
  • Explore the Spring ApplicationContext

a. Application Started

Create a new class Startup, annotate it with @Component, and have it implement the CommandLineRunner interface (you'll import org.springframework.boot.CommandLineRunner).

This will require you to implement a run method, which you can do like this:

public void run(String... args) throws Exception {
  System.out.println("Application started...");

Run the application and look for when the Application started... string is displayed.

b. ApplicationContext Contents

Remove the run method from above and add the following:

private ApplicationContext applicationContext;

public void run(String... args) throws Exception {
  BeanDefinitionRegistry beanDefinitionRegistry = (BeanDefinitionRegistry) this.applicationContext;
  String[] beans = applicationContext.getBeanDefinitionNames();
  for (String bean : beans) {
    System.out.println("Bean name: " + bean);
    BeanDefinition beanDefinition = beanDefinitionRegistry.getBeanDefinition(bean);
    if (beanDefinition.getBeanClassName() != null) {
      if (beanDefinition.getBeanClassName().startsWith("com.tedmyoung")) {
        System.out.println("  --> Class name: " + beanDefinition.getBeanClassName() + ", scope: " + beanDefinition.getScope());

In the output, you'll see all of the beans registered in the Spring ApplicationContext container. For those classes that are part of this project, the full classname is displayed.

c. Clean up

Once you're done exploring the output, you can delete this Startup class, or remove the @Component annotation, so that it doesn't slow down the startup of our application.