Spring
Spring Boot
Java
Startup Method
Application Initialization

Execute method on startup in Spring

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In the world of Java enterprise development, Spring Framework stands as a cornerstone for building robust, scalable, and maintainable applications. One of Spring's core principles is to manage the application lifecycle efficiently. Among the various techniques employed by Spring to cater to this is the ability to run specific code at startup. This is primarily accomplished through the use of the CommandLineRunner and ApplicationRunner interfaces, which allow developers to execute a piece of logic once the application context is fully initialized but before it is made available to serve requests.

The Role of CommandLineRunner and ApplicationRunner

CommandLineRunner

The CommandLineRunner interface is a part of the org.springframework.boot package and it enables developers to execute code upon application startup. The run method gets executed just after the Spring Application Context is loaded and right before the Spring Boot application is completed.

Here is the method signature for CommandLineRunner:

java
1@FunctionalInterface
2public interface CommandLineRunner {
3    void run(String... args) throws Exception;
4}

The run method can accept an array of strings that represent the command line arguments when the application is started. This is useful for executing startup logic based on external parameters.

ApplicationRunner

The ApplicationRunner interface is similar to CommandLineRunner, but it provides more granular access to the application's startup arguments. The interface is defined as follows:

java
1@FunctionalInterface
2public interface ApplicationRunner {
3    void run(ApplicationArguments args) throws Exception;
4}

The key difference here is that ApplicationRunner works with ApplicationArguments, a more structured form of command line arguments which provides easy access to both the raw arguments and the parsed options.

Execution Order

The execution order of CommandLineRunner and ApplicationRunner beans can be controlled using the @Order annotation or by implementing the org.springframework.core.Ordered interface. Without specifying a specific order, the execution is unguaranteed among multiple beans of the same type.

Example

Below is an example demonstrating how to use CommandLineRunner:

java
1import org.springframework.boot.CommandLineRunner;
2import org.springframework.core.annotation.Order;
3import org.springframework.stereotype.Component;
4
5@Component
6@Order(1)
7public class StartupRunner implements CommandLineRunner {
8
9    @Override
10    public void run(String... args) throws Exception {
11        System.out.println("Application started with CommandLineRunner");
12    }
13}

And using ApplicationRunner:

java
1import org.springframework.boot.ApplicationArguments;
2import org.springframework.boot.ApplicationRunner;
3import org.springframework.core.annotation.Order;
4import org.springframework.stereotype.Component;
5
6@Component
7@Order(2)
8public class AppStartupRunner implements ApplicationRunner {
9
10    @Override
11    public void run(ApplicationArguments args) throws Exception {
12        System.out.println("Application started with ApplicationRunner");
13        if (args.containsOption("debug")) {
14            System.out.println("Debugging is enabled.");
15        }
16    }
17}

In this example, StartupRunner will execute before AppStartupRunner due to the specified order.

Key Differences

To summarize the differences between CommandLineRunner and ApplicationRunner, here's a quick comparison:

FeatureCommandLineRunnerApplicationRunner
Argument HandlingRaw String argumentsStructured with ApplicationArguments
Access to OptionsNot directly possibleAvailable via ApplicationArguments.containsOption()
PurposeExecute logic post application initializationExecute logic post application initialization
Interfacerun(String... args)run(ApplicationArguments args)
Common Use CaseInitialize resources, run code post-startupAccess startup options, conditional startup logic
Execution ControlVia @Order or Ordered interfaceVia @Order or Ordered interface

Additional Details

Subtopic: Using @PostConstruct

Another technique to execute code on startup is the use of @PostConstruct, a JSR-250 annotation. It is placed on a method to execute it once after the dependency injection is done.

java
1import javax.annotation.PostConstruct;
2import org.springframework.stereotype.Component;
3
4@Component
5public class PostConstructExample {
6
7    @PostConstruct
8    public void init() {
9        System.out.println("PostConstruct method called after bean initialization");
10    }
11}

However, this method generally runs at bean initialization and not after the full context has started, making it different from CommandLineRunner and ApplicationRunner.

Subtopic: Best Practices

  1. Avoid Heavy Lifting: Perform only necessary startup tasks. Avoid long-running operations which may delay application startup.
  2. Decoupling Logic: If the startup logic is extensive, consider dividing it into smaller beans or services, focusing on single responsibilities.
  3. Exception Handling: Properly handle exceptions to prevent a failed startup, which might lead to a crashed application.

Conclusion

Executing specific logic at startup is a crucial requirement for many Spring applications. Both CommandLineRunner and ApplicationRunner provide efficient and flexible ways to accomplish this. Through careful implementation and understanding of each interface, developers can ensure their applications start up correctly and efficiently, performing any necessary initialization tasks. Always be aware of the execution order and stick to best practices for a cleaner, more maintainable application.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.