SoFunction
Updated on 2025-04-10

Several common ways to initialize SpringBoot project startup

1. Preface

Usually, in our project development, we often encounter situations where some business code needs to be automatically executed as soon as the service is started.

The following are common initialization scenarios:

1. Database initialization: create tables and load data.

2. Cache initialization: Initialize Redis or other caches. For example, cache configuration information or data dictionary in the database to redis

3. Message queue initialization: Initialize the connection and configuration of the message queue.

4. Timing task initialization: Set the execution of timing tasks.

Security Configuration Initialization: Set default users and permissions.

6. External service connection initialization: Initialize the connection with external services. Wait...

2. Several common ways

1. Use CommandLineRunner or ApplicationRunner interfaces

The CommandLineRunner and ApplicationRunner interfaces can be used to execute custom code when Spring Boot starts. Both provide a run method where you can perform the initialization operations you need at startup.

The run(String... args) method of the CommandLineRunner interface receives command line parameters passed in at startup.
The run(ApplicationArguments args) method of the ApplicationRunner interface receives parameters at the start of the Spring Boot application, which can be in key-value pair formats.

CommandLineRunner Example

@Component
public class StartupRunner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        // Initialization logic executed at application startup        ("Execute initialization operation when the application starts...");
        // You can perform some data loading, configuration initialization and other operations here    }
}

ApplicationRunner Example

@Component
public class ApplicationStartupRunner implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        ("Execute initialization operation when the application starts...");
    }
}

2. Use @PostConstruct annotation

The @PostConstruct annotation method will be automatically executed after Spring completes the initialization of all beans. It is usually used to perform some initialization logic, such as loading configuration, initializing data, etc.

@Component
public class MyStartupService {

    @PostConstruct
    public void init() {
        // This is the code executed after Spring completes all bean initialization        ("Spring container initialization is completed, perform initialization operation...");
    }
}

3. Use @EventListener to listen for ApplicationReadyEvent or ContextRefreshedEvent

Spring provides a variety of events that can perform initialization operations when these events are triggered. For example, the ApplicationReadyEvent event fires after the Spring Boot application is fully started, and the ContextRefreshedEvent event fires after the Spring context refreshes.

Example: Listen to ApplicationReadyEvent using @EventListener

@Component
public class StartupEventListener {

    @EventListener()
    public void onApplicationReady() {
        // Actions performed after the application is fully started        ("The Spring Boot application is started and can perform initialization operations...");
    }
}

Example: Use @EventListener to listen for ContextRefreshedEvent

@Component
public class ContextRefreshListener {

    @EventListener()
    public void onContextRefreshed() {
        // Actions performed when Spring container refresh        ("Spring container is refreshed and performs initialization operation...");
    }
}

4. Implement the interface and rewrite the afterPropertiesSet() method

The InitializingBean interface only contains one method afterPropertiesSet(). All classes that inherit the InitializingBean interface will be called during initialization;
How to use it is divided into three steps:

1. Managed by spring           2. Implement the InitializingBean interface           3. Rewrite the afterPropertiesSet method

@Component
public class InitializationBeanTest implements InitializingBean{
    private static final Logger LOG = ();
 
    @Override
    public void afterPropertiesSet() throws Exception {
        ("InitializingBean is starting....");
        //Initialization operation    }
}

5. Start using ApplicationRunner or CommandLineRunner configuration conditions

You can control some initialization logic to execute only in a specific environment through @Profile or other conditional annotations.

Example: Perform initialization according to @Profile conditions

@Component
@Profile("dev")  // Execute only in dev configurationpublic class DevStartupRunner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        ("Perform initialization operations in the development environment...");
    }
}

6. Customize Banner with Spring Boot

Spring Boot supports custom boot content by configuring banner content. This method is suitable for displaying some custom welcome messages or logos.

@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication();
        ((environment, sourceClass, out) -> ("My Custom Banner!"));
        (args);
    }
}

7. Initialize the data (for example: initialize the database or other resources using the @Bean method)

You can also configure Spring Boot application to initialize data when it starts, or to initialize connections for external services through the @Bean method.

Example: Initialize the database

@Configuration
public class DataInitConfig {

    @Bean
    public CommandLineRunner initializeData() {
        return args -> {
            // Load or initialize data when the application starts            ("Initialize the data...");
            // You can call database services or other business logic here        };
    }
}

Summarize

This is the article about several common methods of initialization operations during SpringBoot project startup. For more relevant content on initialization at SpringBoot project startup, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!