How to dynamically load database configurations in Spring Boot?

In Spring Boot, static loading of database configurations can be achieved by setting them in the application.properties or application.yml files. However, for dynamic loading of database configurations, the dynamic configuration feature of Spring Boot can be used.

Below are the steps to implement dynamically loading database configuration.

  1. Add necessary dependencies to the pom.xml file, including Spring Boot Starter, Spring Boot DevTools, and Spring Boot Configuration Processor.
  2. Create a configuration class
    Create a class, like DatabaseConfig.java, to load database configurations. Use the @ConfigurationProperties annotation in this class to bind properties from the configuration file.
  3. The class DatabaseConfig is annotated with @Component and @ConfigurationProperties with a prefix of “database”. It holds properties for the url, username, and password of the database.
  4. Add database configuration properties in the application.properties or application.yml file.
  5. .properties file for application:
  6. The database is located at jdbc:mysql://localhost:3306/mydb with the username as root and password as root.
  7. configuration file named application.yml
  8. database connection details:
    url: jdbc:mysql://localhost:3306/mydb
    username: root
    password: root
  9. Load the configuration class in the main class by using the @EnableConfigurationProperties annotation.
  10. Declare the following imports in order to utilize the Spring Boot framework: SpringApplication, SpringBootApplication, and EnableConfigurationProperties. SpringApplication will be used to run the application, while EnableConfigurationProperties will enable the use of DatabaseConfig class for configuration properties. The main method within the Application class will run the application.

Now, you can inject the DatabaseConfig class in your code and use its properties.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MyService {

    private final DatabaseConfig databaseConfig;

    @Autowired
    public MyService(DatabaseConfig databaseConfig) {
        this.databaseConfig = databaseConfig;
    }

    public void doSomething() {
        String url = databaseConfig.getUrl();
        String username = databaseConfig.getUsername();
        String password = databaseConfig.getPassword();

        // 使用数据库配置执行操作
    }

}

This way, you can dynamically load database configurations. When the database configurations in the configuration file change, there is no need to restart the application – the changes will take effect automatically.

bannerAds