SoFunction
Updated on 2025-03-02

Implement dynamically configured database loading based on SpringBoot

1. Background

There is a requirement for the project, and it is expected to passSet a switch in the configuration file to determine whether to load the database. Require:

  • When the value of the switch istrueload the database;

  • When the value of the switch isfalseor the database is not loaded without this configuration.

2. Specific implementation

2.1 Database related configuration

Add configuration into determine whether to load database-related configurations.

spring:
  datasource:
    #Enable MySQL    enabled: true
    driver-class-name: 
    url: jdbc:mysql://localhost:3306/test?createDatabaseIfNotExist=true&useSSL=false&serverTimezone=GMT%2b8&characterEncoding=utf8&connectTimeout=30000&socketTimeout=30000&autoReconnect=true&cachePrepStmts=true&useServerPrepStmts=true
    username: root
    password: 123456
    type: 
    hikari:
      # Connection pool name      pool-name: MyHikariCP
      #The minimum idle connection, default value 10, less than 0 or greater than maximum-pool-size, will be reset to maximum-pool-size      minimum-idle: 10
      #The maximum number of connections to the connection pool, the default is 10 (number of cpu cores * 2 + number of hard disks)      maximum-pool-size: 30
      #Idle connection timeout time, default value is 600000 (10 minutes), greater than or equal to max-lifetime and max-lifetime>0, will be reset to 0; not equal to 0 and less than 10 seconds, will be reset to 10 seconds.      idle-timeout: 600000
      #The maximum survival time of the connection, not equal to 0 and less than 30 seconds, will be reset to the default value for 30 minutes. The setting should be shorter than the timeout set by mysql      max-lifetime: 1800000
      #Connection timeout: milliseconds, less than 250ms, otherwise it will be reset to the default value for 30 seconds      connection-timeout: 30000
      # Query statement used to test whether the connection is available      connection-test-query: SELECT 1

  jpa:
    database: mysql
    show-sql: false
    hibernate:
      naming:
        physical-strategy: 
      ddl-auto: update
    properties:
      hibernate:
        jdbc:
          batch_size: 100
        dialect: .MySQL5InnoDBDialect
        enable_lazy_load_no_trans: true
    open-in-view: false

2.2 Add annotations to start the class

Start the class to add annotations@SpringBootApplication(exclude = { }), means that the database-related configuration is not automatically loaded by default.

@SpringBootApplication(exclude = {  })
public class OcrsrvcApplication {
    public static void main(String[] args) {
        (, args);
    }
}

2.3 Added DataSourceConfig configuration class

Added a data source configuration class for customizing the creation of data sources.

Use Notes@ConditionalOnProperty, this allows you to decide whether to load a component based on the value of a specific property.

@Configuration
@ConditionalOnProperty(name = "", havingValue = "true")
@Slf4j
public class DataSourceConfig {

    @Value("${}")
    private String jdbcUrl;

    @Value("${-class-name}")
    private String driverClassName;

    @Value("${}")
    private String username;

    @Value("${}")
    private String password;

    @Value("${-name}")
    private String poolName;

    @Value("${-idle}")
    private int minimumIdle;

    @Value("${-pool-size}")
    private int maximumPoolSize;

    @Value("${-timeout}")
    private long idleTimeout;

    @Value("${-lifetime}")
    private long maxLifetime;

    @Value("${-timeout}")
    private long connectionTimeout;

    @Value("${-test-query}")
    private String connectionTestQuery;

    @Bean
    public DataSource dataSource() {

        ("====Loading the database===");
        HikariConfig hikariConfig = new HikariConfig();

        (jdbcUrl);
        (driverClassName);
        (username);
        (password);
        (poolName);
        (minimumIdle);
        (maximumPoolSize);
        (idleTimeout);
        (maxLifetime);
        (connectionTimeout);
        (connectionTestQuery);

        return new HikariDataSource(hikariConfig);
    }
}

2.4 Related business logic adjustments

Related business logic involving the use of databases can beXxxRepositoryAdd annotations to the class@ConditionalOnProperty(name = "", havingValue = "true") , which means that the corresponding components will be loaded only when the database is enabled.

Use Notes@Autowired(required = false)injectionXxxRepository, means that the allow is empty, avoiding errors when the bean does not exist

@Autowired(required = false)  
private XxxRepository xxxRepository;

This is the article about the loading of dynamically configured databases based on SpringBoot. For more related loading content of SpringBoot configuration databases, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!