{{announcement.body}}
{{announcement.title}}

How to Execute Code on Spring Application Start-Up

DZone 's Guide to

How to Execute Code on Spring Application Start-Up

Have you ever encountered a situation where you’ve to perform some tasks immediately after the Spring/SpringBoot application starts?

· Microservices Zone ·
Free Resource

Introduction

Have you ever encountered a situation where you’ve to perform some tasks 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 it. Here I’m gonna 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. ContextStartedEvent event triggered at the time of context gets started. ContextRefreshedEvent event triggered at the time of context gets started or refreshed.

Java
 




x
22


1
@Component
2
public class EventHandler {
3
    @EventListener(ContextStartedEvent.class)
4
    public void handleContextStartEvent(ContextStartedEvent e) {
5
        // Write your code here
6
    }
7
 
          
8
    @EventListener(ContextRefreshedEvent.class)
9
    public void handleContextRefreshEvent(ContextRefreshedEvent e) {
10
        // Write your code here
11
    }
12
    // Or you can handle both the events in 1 method  
13
    
14
    @EventListener({ContextStartedEvent.class, ContextRefreshedEvent.class})
15
    public void handleBoth(ApplicationContextEvent e) {
16
        if (e instanceof ContextStartedEvent) {
17
 
          
18
        } else {
19
 
          
20
        }
21
    }
22
}



ApplicationRunner

SpringBoot provides an interface called ApplicationRunner, any bean implementing this interface should run when that contained in the SpringApplication.

Java
 




xxxxxxxxxx
1
14


 
1
@Component
2
public class DBInitializer implements ApplicationRunner {
3
    
4
    private final UserRepository userRepository;
5
    
6
    private DBInitializer(UserRepository userRepository) {
7
        this.userRepository = userRepository;
8
    }
9
    
10
    @Override
11
    public void run(ApplicationArguments args) throws Exception {
12
        // Initialize user here
13
    }
14
}



or the above can be used

Java
 




x
10


1
@Configuration
2
public class Config {
3
    
4
    @Bean
5
    public ApplicationRunner initializeUser(UserRepository userRepository) {
6
        return args -> {
7
            // Initialize user here
8
        };
9
    }
10
}



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. i.e.

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

So the method call to

  1. getOptionNames() in ApplicationArguments will return set of arguments - [‘source’, ‘print-only’, ‘target’]
  2. containsOption(String name) checks if the argument contains in the given input
  3. getOptionValues(name) returns a list of option values. getOptionValues('source') will return list - [‘/usr/local’]
Topics:
java, microservices, spring context, springboot, springbootmicroservices

Published at DZone with permission of Jitendra Bisht . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}