Enterprise Java

How to Run a CommandLineRunner Bean Conditionally in Spring Boot

CommandLineRunner in Spring is an interface allowing the execution of code when an application starts. It provides a callback method run(String... args) where you can place your startup logic. This is useful for tasks like data initialization, database migration, or any other setup required at application startup. Implement the CommandLineRunner interface, and Spring Boot will automatically detect and execute your code upon application startup, ensuring seamless integration of custom initialization tasks into your Spring application. Let us delve to understand how to run a CommandLineRunner bean conditionally in Spring boot.

1. Using @ConditionalOnProperty annotation

In Spring Boot, you can conditionally execute a CommandLineRunner bean using @ConditionalOnProperty. This annotation allows you to specify a condition based on the value of a configuration property. If the specified property is present in the configuration and meets certain criteria, the bean will be created and executed during application startup.

1.1 Example Usage

Consider a scenario where you want to execute a CommandLineRunner bean only if a specific property is set in the application’s configuration. Let’s say the property is named myapp.runStartupTask, and you want the bean to run only when this property is set to true.

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

@Component
@ConditionalOnProperty(name = "myapp.runStartupTask", havingValue = "true")
public class MyStartupRunner implements CommandLineRunner {

  @Override
  public void run(String...args) throws Exception {
    // Your startup logic here
    System.out.println("Executing startup task...");
  }
}

In this example, the MyStartupRunner class implements the CommandLineRunner interface and is annotated with @Component. Additionally, it is annotated with @ConditionalOnProperty, specifying that it should only be created if the myapp.runStartupTask property is set to true. When the application starts, Spring Boot checks the value of this property, and if it meets the specified criteria, it creates and executes the bean.

By leveraging @ConditionalOnProperty, you can control the execution of CommandLineRunner beans based on the configuration of your Spring Boot application, allowing for flexible and conditional startup logic.

2. Using Environment

In Spring Boot, you can conditionally execute a CommandLineRunner bean based on the application’s environment using the Environment object. This allows you to check properties or profiles to determine whether the bean should be executed during application startup.

2.1 Example Usage

Let’s assume you have an application property named myapp.runStartupTask, and you want to execute the CommandLineRunner bean only when this property is set to true.

import org.springframework.boot.CommandLineRunner;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class MyStartupRunner implements CommandLineRunner, EnvironmentAware {

  private Environment environment;

  @Override
  public void setEnvironment(Environment environment) {
    this.environment = environment;
  }

  @Override
  public void run(String...args) throws Exception {
    if (environment.getProperty("myapp.runStartupTask", Boolean.class, false)) {
      // Your startup logic here
      System.out.println("Executing startup task...");
    } else {
      System.out.println("Startup task is not enabled.");
    }
  }
}

In this example, the MyStartupRunner class implements both the CommandLineRunner interface and the EnvironmentAware interface to access the application’s environment. Inside the run method, it checks if the myapp.runStartupTask property is set to true using the Environment object. If the condition is met, the startup logic is executed.

By utilizing the Environment object, you can conditionally execute CommandLineRunner beans based on properties or profiles in your Spring Boot application, providing flexibility in managing startup tasks.

3. Using Spring Profiles

In Spring Boot, you can conditionally execute a CommandLineRunner bean based on the active profiles. This allows you to define different sets of beans and configurations for different environments or scenarios.

3.1 Example Usage

Let’s consider a scenario where you want to execute a CommandLineRunner bean only when a specific profile is active, such as the ‘production’ profile.

import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

@Component
@Profile("production")
public class MyStartupRunner implements CommandLineRunner {

  @Override
  public void run(String...args) throws Exception {
    // Your startup logic here
    System.out.println("Executing startup task...");
  }
}

In this example, the MyStartupRunner class implements the CommandLineRunner interface and is annotated with @Component. Additionally, it is annotated with @Profile("production"), indicating that it should only be created and executed when the ‘production’ profile is active.

When you start your Spring Boot application with the ‘production’ profile, Spring Boot will detect the active profile and create and execute beans annotated with @Profile("production"), ensuring that the MyStartupRunner bean is only executed in the production environment.

By leveraging Spring Profiles, you can easily manage the execution of CommandLineRunner beans based on the active environment, allowing for fine-grained control over the initialization process of your Spring Boot application.

4. Conclusion

In this article, we explored various techniques for conditionally executing a CommandLineRunner bean in a Spring Boot application. Starting with the use of @ConditionalOnProperty, we learned how to execute the bean based on the presence and value of a configuration property. This approach provides flexibility in defining startup behavior depending on configurable properties.

Next, we delved into using the Environment object to conditionally execute the bean by checking properties or profiles. By accessing the application’s environment, we can dynamically control the initialization process based on runtime conditions.

Furthermore, we explored the use of Spring Profiles to execute the CommandLineRunner bean selectively based on the active profile. This allows for tailored initialization logic for different environments, promoting environment-specific configuration.

Lastly, we discussed checking the presence of other beans using @ConditionalOnBean, enabling conditional execution based on the availability of dependencies. This technique facilitates modularization and ensures that certain tasks are performed only when required dependencies are present.

In conclusion, Spring Boot offers several mechanisms for conditionally executing CommandLineRunner beans, allowing developers to tailor the application’s startup behavior to specific requirements. Whether it’s based on configuration properties, environment conditions, profiles, or bean dependencies, these techniques empower developers to create more flexible and dynamic initialization processes in their Spring Boot applications.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button