Java > Spring Framework > Spring Boot > Creating Spring Boot Applications

Creating a Spring Boot Application with Command Line Runner

This example demonstrates how to use the CommandLineRunner interface to execute code after the Spring Boot application context has been initialized. This is useful for performing tasks such as initializing data or running scheduled jobs.

Project Setup (pom.xml)

This pom.xml file sets up a basic Spring Boot project. It inherits from spring-boot-starter-parent and includes the spring-boot-starter dependency, which provides core Spring Boot functionality. The Spring Boot Maven plugin is configured for packaging.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>springboot-commandlinerunner</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot-commandlinerunner</name>
    <description>Demo project for Spring Boot CommandLineRunner</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <java.version>17</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Main Application Class

The @SpringBootApplication annotation enables auto-configuration, component scanning, and configuration. The SpringApplication.run() method starts the Spring application context.

package com.example.springbootcommandlinerunner;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootCommandlinerunnerApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootCommandlinerunnerApplication.class, args);
    }

}

CommandLineRunner Implementation

This class implements the CommandLineRunner interface. The @Component annotation makes it a Spring-managed bean. The run() method is executed after the application context is initialized. It logs a message and iterates through any command-line arguments passed to the application.

package com.example.springbootcommandlinerunner;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class MyCommandLineRunner implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(MyCommandLineRunner.class);

    @Override
    public void run(String... args) throws Exception {
        logger.info("CommandLineRunner executed!");
        for (String arg : args) {
            logger.info("Argument: " + arg);
        }
    }

}

Concepts Behind the Snippet

The CommandLineRunner interface provides a way to execute code after the Spring Boot application has started. It's useful for tasks that need to be performed during application startup, such as database initialization or configuration loading. The @Component annotation makes the class a Spring-managed bean, allowing it to be automatically discovered and instantiated.

Real-Life Use Case

You can use CommandLineRunner to seed a database with initial data, create default users, or perform other setup tasks. It's also useful for running scheduled jobs or processing command-line arguments.

Best Practices

  • Use logging to track the execution of your CommandLineRunner.
  • Handle exceptions gracefully to prevent the application from crashing during startup.
  • Avoid performing long-running tasks in the run() method, as this can delay the application startup.

Interview Tip

Be prepared to explain the purpose of the CommandLineRunner interface and how it's used to execute code during application startup. Also, understand how to handle command-line arguments.

When to use them

Use CommandLineRunner when you need to execute code once, immediately after the Spring Boot application context is initialized. It is ideal for initialization tasks, one-time data processing, or tasks based on command line arguments.

Memory Footprint

The CommandLineRunner itself has a minimal impact on memory footprint. However, the tasks executed within the run() method can affect memory usage depending on their complexity and data processing requirements.

Alternatives

Alternatives to CommandLineRunner include:

  • ApplicationListener<ContextRefreshedEvent>: Allows you to execute code when the application context is refreshed.
  • @PostConstruct: Allows you to execute code after a bean has been initialized.
  • Spring Batch: A framework for building robust batch processing applications.

Pros

  • Simple to implement: The CommandLineRunner interface is easy to use and understand.
  • Executed during startup: Ensures that tasks are performed before the application starts handling requests.
  • Access to command-line arguments: Allows you to process command-line arguments passed to the application.

Cons

  • Limited scope: Only suitable for tasks that need to be executed once during startup.
  • Can delay startup: Long-running tasks can delay the application startup.
  • Tight coupling: Can lead to tight coupling between the application and the initialization tasks.

FAQ

  • What is the purpose of the CommandLineRunner interface?

    The CommandLineRunner interface allows you to execute code after the Spring Boot application context has been initialized.

  • How do I access command-line arguments in a CommandLineRunner?

    The run() method of the CommandLineRunner interface receives an array of strings containing the command-line arguments.

  • When is the run() method executed?

    The run() method is executed after the Spring Boot application context has been initialized and all beans have been created.