How to load a specific configuration file in Spring Boot?

Spring Boot can load specific configuration files using the @ConfigurationProperties annotation. The specific steps are as follows:

  1. Create a configuration file in the resources directory of the project, such as application-dev.properties, where dev is the specified environment name.
  2. Add the @ConfigurationProperties annotation to the configuration class in the Spring Boot project and set the prefix attribute to the prefix in the configuration file, such as “spring.datasource”. Also, set the locations attribute to the path of the configuration file, for example, “classpath:application-${spring.profiles.active}.properties”.

The example code is shown below:

@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
@PropertySource(value = {"classpath:application-${spring.profiles.active}.properties"})
public class DataSourceConfig {
    private String url;
    private String username;
    private String password;

    // getters and setters
}
  1. Add the following dependencies to the pom.xml file.
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
  1. Set the “spring.profiles.active” property in the application.properties or application.yml file to the specified environment, such as “dev”.
spring.profiles.active=dev

Or alternatively

spring:
  profiles:
    active: dev

In this way, Spring Boot will load the corresponding configuration information based on the specified configuration file.

bannerAds