What happens when you have default yaml or properties file along with the profile specific yml or properties files. eg: you have application.yml and application-dev.yml, application-test.yml, application-prod.yml
1. Default Behavior (No Active Profile)
Only
application.yml
is loadedAll other profile-specific files (
-dev.yml
,-test.yml
,-prod.yml
) are ignoredUseful for shared configurations (e.g., app name, default server port)
2. When a Profile is Activated
If you activate a profile (e.g., dev
):
application.yml
is loaded first (base config)application-dev.yml
is merged on top, overriding matching propertiesOther profile files (
-test.yml
,-prod.yml
) are ignored
Example:
# application.yml (shared) server: port: 8080 logging: level: root: INFO # application-dev.yml (dev-only) logging: level: root: DEBUG org.hibernate.SQL: TRACE
Result (--spring.profiles.active=dev
):
server: port: 8080 # From base logging: level: root: DEBUG # Overridden by dev org.hibernate.SQL: TRACE # Added by dev
3. Key Rules
Rule | Explanation |
---|---|
Profile-specific files override base | application-dev.yml wins over application.yml |
Last profile wins | If multiple profiles are active (dev,test ), the rightmost profile's config takes precedence |
Non-conflicting properties merge | Unique properties from all files are combined |
spring.profiles.include | Force-include additional profiles (e.g., spring.profiles.include: db,security ) |
4. How to Activate Profiles
Option 1: Command Line
java -jar app.jar --spring.profiles.active=prod
Option 2: Environment Variable
export SPRING_PROFILES_ACTIVE=test # Linux/macOS set SPRING_PROFILES_ACTIVE=test # Windows
Option 3: In application.yml
spring: profiles: active: dev # Default profile (not recommended for production)
5. Advanced: Multi-Profile Activation
You can activate multiple profiles (e.g., dev + db-mysql
):
--spring.profiles.active=dev,db-mysql
Spring Boot merges them in order (rightmost profile wins conflicts).
6. Best Practices
application.yml
→ Store default/shared configsapplication-{profile}.yml
→ Store environment-specific overridesNever commit secrets → Use
application-{profile}.yml
with Vault/Env vars for prod credentialsUse
spring.config.activate.on-profile
(YAML only) to conditionally include sections:# In application.yml spring: config: activate: on-profile: "dev" logging: level: root: DEBUG
7. Debugging Configuration
Check which profiles are active and property sources:
# Enable debug mode java -jar app.jar --debug
Look for:
The following profiles are active: dev Property Sources: - application.yml - application-dev.yml
Summary
Base + Profile-Specific: Configs merge, with profile files overriding defaults
Profile Activation: Controls which
-{profile}.yml
files are loadedOrder Matters: Last profile in a comma-separated list has highest priority
This system allows clean separation of environments while avoiding duplication.
No comments:
Post a Comment