How does Spring Boot read multiple configuration files?

In Spring Boot, multiple configuration files can be read using the @PropertySource annotation.

Step 1: Create multiple configuration files.

Create multiple configuration files, such as config1.properties and config2.properties, in the src/main/resources directory.

Step 2: Create a configuration class.

In a Spring Boot application’s configuration class, use the @PropertySource annotation to specify the configuration file to be read. The code example is as follows:

@Configuration
@PropertySource({"classpath:config1.properties", "classpath:config2.properties"})
public class AppConfig {

    // 使用@Value注解来读取配置文件中的值
    @Value("${property1}")
    private String property1;

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

    // ...

    // 其他配置和方法
}

In the example above, the @PropertySource annotation specifies the file path of the configuration to be read, and it is possible to specify multiple configuration files at the same time.

Step 3: Utilize the configuration values.

In places where configuration values are needed, you can retrieve the values from the configuration file using the @Value annotation. For example:

@Service
public class MyService {

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

    // ...

    // 其他代码
}

In the example above, the @Value annotation is used to read the value of the property1 configuration item.

Note: if there are duplicate configuration options in multiple configuration files, the configuration option in the later file will override the one in the earlier file.

bannerAds