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.
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:
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:
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:
And using ApplicationRunner:
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:
| Feature | CommandLineRunner | ApplicationRunner |
| Argument Handling | Raw String arguments | Structured with ApplicationArguments |
| Access to Options | Not directly possible | Available via ApplicationArguments.containsOption() |
| Purpose | Execute logic post application initialization | Execute logic post application initialization |
| Interface | run(String... args) | run(ApplicationArguments args) |
| Common Use Case | Initialize resources, run code post-startup | Access startup options, conditional startup logic |
| Execution Control | Via @Order or Ordered interface | Via @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.
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
- Avoid Heavy Lifting: Perform only necessary startup tasks. Avoid long-running operations which may delay application startup.
- Decoupling Logic: If the startup logic is extensive, consider dividing it into smaller beans or services, focusing on single responsibilities.
- 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
- Executing an update/delete query in the JQPL query
- ExecutorService, how to wait for all tasks to finish
- ExecutorService, how to wait for all tasks to finish
- ExecutorService that interrupts tasks after a timeout
- Executors.newCachedThreadPool versus Executors.newFixedThreadPool
- Executors.newCachedThreadPool versus Executors.newFixedThreadPool
- Explicit casting from super-class to sub-class
- Explicitly calling a default method in Java

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack 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.