Skip to content

Checking your reading list…

Retry verification

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

How to Load Initial Data into Spring Boot 3.2.5: Runners, Beans, and SQL Scripts

How to Load Initial Data into Spring Boot 3.2.5: Runners, Beans, and SQL Scripts

This guide explains why pre‑loading initial data is essential for Spring Boot applications and demonstrates four practical methods—CommandLineRunner/ApplicationRunner, bean initialization with @PostConstruct, SQL script execution, and @Sql annotation for tests—complete with code snippets and configuration details.

Environment: Spring Boot 3.2.5

1. Introduction

Loading initial data into a database is a common requirement for many applications. It simplifies setup, ensures consistency, provides default values, and supplies realistic data for development and testing.

Application setup: Pre‑populating data streamlines the initial configuration, allowing the application to start immediately without manual data insertion.

Consistency and integrity: Shared initial data guarantees that all instances of the application start with the same baseline, avoiding inconsistencies.

Default values: Default configuration values give users a ready‑to‑use baseline.

Development data: Developers and testers can work with realistic data sets.

2. Practical examples

2.1 Using CommandLineRunner / ApplicationRunner

@Component
public class PackDataInitializer implements CommandLineRunner {
    private final UserRepository userRepository;
    public PackDataInitializer(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
    @Override
    public void run(String... args) {
        User user1 = new User("Pack", "[email protected]");
        User user2 = new User("Jack", "[email protected]");
        userRepository.saveAll(Arrays.asList(user1, user2));
    }
}

This component runs automatically during Spring Boot startup to insert the initial users.

2.2 Bean initialization with @PostConstruct or InitializingBean

@Component
public class PackDataLoader {
    private final StringRedisTemplate stringRedisTemplate;
    public PackDataLoader(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    @PostConstruct
    public void loadInitialData() {
        ValueOperations<String, String> vo = this.stringRedisTemplate.opsForValue();
        vo.set("a", "...");
        vo.set("b", "...");
        // ...
    }
}

2.3 SQL scripts

Spring Boot can execute schema.sql and data.sql placed on the classpath.

-- script.sql
CREATE TABLE IF NOT EXISTS users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    password VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL,
    enabled BOOLEAN NOT NULL
);
CREATE TABLE IF NOT EXISTS roles (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL
);
-- data.sql
INSERT INTO roles (name) VALUES ('ROLE_USER'), ('ROLE_ADMIN');
INSERT INTO users (username, password, email, enabled) VALUES
('user1','123456','[email protected]',true),
('user2','123456','[email protected]',true),
('admin','admin123','[email protected]',true);

Configure Spring Boot to run them:

spring:
  sql:
    init:
      mode: always
      schema-locations: classpath:db/script.sql
      data-locations: classpath:db/data.sql

For non‑embedded databases you may need to set spring.sql.init.platform and name scripts accordingly (e.g., schema-mysql.sql).

2.4 Test environment with @Sql

@SpringBootTest
@AutoConfigureTestDatabase
@Sql(scripts = {"/data.sql", "/schema.sql"})
public class AppTests {
    @Test
    public void test1() {}
    @Test
    public void test2() {}
}

The @Sql annotation can also be placed on individual test methods to run specific scripts before that method.

Typically the project uses JPA for basic CRUD operations and MyBatis for more complex queries.

Spring Boot startup log
Spring Boot startup log
Script naming convention
Script naming convention
About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

Report an issue with this article
testingBackend DevelopmentSpring BootCommandLineRunnerSQL ScriptsData Initialization

Reader feedback

Was this useful?

Useful0

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion