How to execute code on a Spring application start-up

Introduction

Have you ever encountered a situation where you’ve to performed some task immediately after the Spring/SpringBoot application starts (i.e., initialize some data into the database, initialize application-level constants, make an API call, etc.)?

There are several ways to achieve this. In this shot I’m going to discuss:

  1. Application events
  2. ApplicationRunner

Technologies used

  1. Java 11
  2. Spring Boot 2.2.4
  3. Gradle 6.0.1

Application events

The Spring framework triggers various events. For our use case, we’ll be more interested in ContextStartedEvent and ContextRefreshedEvent. The ContextStartedEvent event is triggered at the time that the context gets started. The ContextRefreshedEvent event is triggered at the time that the context gets started or refreshed.

@Component
public class EventHandler {
    @EventListener(ContextStartedEvent.class)
    public void handleContextStartEvent(ContextStartedEvent e) {
        // Write your code here
    }

    @EventListener(ContextRefreshedEvent.class)
    public void handleContextRefreshEvent(ContextRefreshedEvent e) {
        // Write your code here
    }
    // Or you can handle both the events in 1 method  
    
    @EventListener({ContextStartedEvent.class, ContextRefreshedEvent.class})
    public void handleBoth(ApplicationContextEvent e) {
        if (e instanceof ContextStartedEvent) {

        } else {

        }
    }
}

ApplicationRunner

SpringBoot framework provides an interface ApplicationRunner. When we implement any class with ApplicationRunner and register it as spring bean, then the bean will be executed by Spring framework on the application startup, or whenever Spring context is ready.

@Component
public class DBInitializer implements ApplicationRunner {
    
    private final UserRepository userRepository;
    
    private DBInitializer(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
    
    @Override
    public void run(ApplicationArguments args) throws Exception {
        // Initialize user here
    }
}

or the above can be used

@Configuration
public class Config {
    
@Bean
    public ApplicationRunner initializeUser(UserRepository userRepository) {
        return args -> {
            // Initialize user here
        };
    }
}

ApplicationRunner provides ApplicationArguments in the run method, which is used to get command line arguments by invoking getSourceArgs(). You can also get the parsed arguments using this class.

Let’s say you’ve passed command-line arguments like, --source /usr/local --print-only --target /tmp/local.

So, the methods to call are:

  1. getOptionNames() in ApplicationArguments will return a set of arguments - [‘source’, ‘print-only’, ‘target’]
  2. containsOption(String name) checks if an argument contains a string
  3. getOptionValues(name) returns list of option values getOptionValues('source') will return list - [’/usr/local’]

Happy coding, enjoy!!

Free Resources

Attributions:
  1. undefined by undefined