Skip to content

Lab 3: Run on Application Startup

Goals

  • Learn about how to run code at startup with the CommandLineRunner
  • Explore the contents of Spring's ApplicationContext

a. Application Started

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

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

@Override
public void run(String... args) throws Exception {
    System.out.println("CommandLineRunner has started...");
}

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

b. ApplicationContext Contents

Stop the application.

Remove the run method from above and replace it with the following:

private final ApplicationContext applicationContext;

public Startup(ApplicationContext applicationContext) {
    this.applicationContext = applicationContext;
}

@Override
public void run(String... args) throws Exception {
    BeanDefinitionRegistry beanDefinitionRegistry = (BeanDefinitionRegistry) this.applicationContext;
    String[] beans = applicationContext.getBeanDefinitionNames();
    Arrays.sort(beans);
    for (String bean : beans) {
        System.out.println("Bean name: " + bean);
        BeanDefinition beanDefinition = beanDefinitionRegistry.getBeanDefinition(bean);
        if (beanDefinition.getBeanClassName() != null) {
            if (beanDefinition.getBeanClassName().startsWith("com.welltestedlearning")) {
                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.

References

CommandLineRunner

For more details, consult the Spring Boot documentation: https://docs.spring.io/spring-boot/docs/2.4.5/reference/htmlsingle/#boot-features-command-line-runner