How to Use Multiple Properties Files in Spring Boot
@PropertySource annotations or by listing them in spring.config.import in application.properties. This allows your application to load configuration from several files and merge them automatically.Syntax
You can load multiple properties files in Spring Boot using the @PropertySource annotation on a configuration class or by using the spring.config.import property in your application.properties or application.yml.
@PropertySource syntax:
@PropertySource({"classpath:file1.properties", "classpath:file2.properties"})loads multiple files.
spring.config.import syntax:
spring.config.import=classpath:file1.properties,classpath:file2.properties
@Configuration
@PropertySource({"classpath:config1.properties", "classpath:config2.properties"})
public class AppConfig {
// Beans and configuration
}Example
This example shows how to load two properties files named config1.properties and config2.properties using @PropertySource. The properties from both files are available for injection using @Value or Environment.
package com.example.demo; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.PropertySource; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @PropertySource({"classpath:config1.properties", "classpath:config2.properties"}) public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } @RestController class MyController { @Value("${app.name}") private String appName; @Value("${app.version}") private String appVersion; @GetMapping("/info") public String info() { return "App: " + appName + ", Version: " + appVersion; } }
Common Pitfalls
1. Missing files: If a properties file is not found, Spring throws an error unless you set ignoreResourceNotFound=true in @PropertySource.
2. Property overriding: Properties in later files override earlier ones. Order matters.
3. Using @PropertySource only works with .properties files, not .yml.
4. For YAML files, use spring.config.import in application.properties or application.yml.
@PropertySource(value = "classpath:optional.properties", ignoreResourceNotFound = true) // This prevents errors if the file is missing
Quick Reference
| Feature | Usage | Notes |
|---|---|---|
| @PropertySource | Load multiple .properties files in config class | Only supports .properties, not YAML |
| spring.config.import | List multiple config files in application.properties | Supports .properties and .yml files |
| ignoreResourceNotFound | Avoid errors if file missing | Use in @PropertySource annotation |
| Property overriding | Last file properties override earlier ones | Order matters in loading files |