Spring多Profile配置文件优先级疑问:属性覆盖规则咨询
Great question! Let me break down exactly how Spring Boot resolves conflicting properties when you have multiple active profiles like dev and personal.
First, let's recap the base loading order:
- Spring Boot always starts by loading the default
application.properties(or.yml) file, regardless of active profiles. - Next, it loads the property files corresponding to each active profile, and these will override any matching properties from the default file.
Now, for the key part when multiple profiles are active:
When you specify profiles in a list (like spring.profiles.active=dev,personal), the last profile in the list has the highest priority. That means:
- Any property defined in
application-personal.propertieswill override the same property inapplication-dev.properties - Both
devandpersonalprofile properties will override the same property in the defaultapplication.properties
Let me give you a concrete example to make it clear:
- Default
application.propertieshasapp.api.url=https://default-api.com application-dev.propertieshasapp.api.url=https://dev-api.comapplication-personal.propertieshasapp.api.url=https://personal-api.com
If you run with spring.profiles.active=dev,personal, the final value of app.api.url will be https://personal-api.com—because personal is the last profile in the active list, its properties take precedence over dev and the default.
A quick way to verify this is to inject the property into a bean and log it, or inspect the Environment object in your application:
@RestController public class PropertyTestController { @Value("${app.api.url}") private String apiUrl; @GetMapping("/api-url") public String getApiUrl() { return apiUrl; } }
Hitting this endpoint will show you the resolved value directly.
One more thing to note: this priority rule applies regardless of how you activate the profiles—whether it's via the spring.profiles.active property, command line arguments (--spring.profiles.active=dev,personal), or even programmatically in your application. The last profile added to the active set will always win out for conflicting properties.
内容的提问来源于stack exchange,提问作者Nickknack

