DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Securing Your Software Supply Chain with JFrog and Azure
Register Today

Trending

  • How To Integrate Microsoft Team With Cypress Cloud
  • Web Development Checklist
  • Top 10 Pillars of Zero Trust Networks
  • Merge GraphQL Schemas Using Apollo Server and Koa

Trending

  • How To Integrate Microsoft Team With Cypress Cloud
  • Web Development Checklist
  • Top 10 Pillars of Zero Trust Networks
  • Merge GraphQL Schemas Using Apollo Server and Koa
  1. DZone
  2. Coding
  3. Frameworks
  4. How to Execute Code on Spring Application Start-Up

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?

Jitendra Bisht user avatar by
Jitendra Bisht
CORE ·
Sep. 16, 20 · Tutorial
Like (5)
Save
Tweet
Share
5.12K Views

Join the DZone community and get the full member experience.

Join For Free

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’]
Spring Framework application

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

Opinions expressed by DZone contributors are their own.

Trending

  • How To Integrate Microsoft Team With Cypress Cloud
  • Web Development Checklist
  • Top 10 Pillars of Zero Trust Networks
  • Merge GraphQL Schemas Using Apollo Server and Koa

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: