Skip to content

Lab 3: Run on Application Startup


  • 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:

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;

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.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.



For more details, consult the Spring Boot documentation: