I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

1. Introduction

In this article we’ll focus on how to run logic at the startup of a Spring application.

2. Running Logic On Startup

Running logic during/after Spring application’s startup is a common scenario, but one that causes multiple problems.

In order to benefit from Inverse of Control, we naturally need to renounce partial control over the application’s flow to the container – which is why instantiation, setup logic on startup, etc needs special attention.

We can’t simply include our logic in the beans’ constructors or call methods after instantiation of any object; we are simply not in control during those processes.

Here, we’re trying to access an autowired field in the constructor. When the constructor is called, the Spring bean is not yet fully initialized. This is problematic because calling not yet initialized fields will of course result in NullPointerExceptions.

Spring gives us a few ways of managing this situation.

2.1. The @PostConstruct Annotation

Javax’s @PostConstruct annotation can be used for annotating a method that should be run once immediately after the bean’s initialization. Keep in mind that the annotated method will be executed by Spring even if there is nothing to inject.

Note: As mentioned in the documentation, multiple CommandLineRunner beans can be defined within the same application context and can be ordered using the @Ordered interface or @Order annotation.

2.7. Spring Boot ApplicationRunner

Similar to CommandLineRunner, Spring boot also provides an ApplicationRunner interface with a run() method to be invoked at application startup. However, instead of raw String arguments passed to the callback method, we have an instance of the ApplicationArgumentsclass.

The ApplicationArguments interface has methods to get argument values that are options and plain argument values. An argument that is prefixed with – – is an option argument.