Concept Explanation
Your database URL differs between your laptop, the test server, and production. Hard-coding it means rebuilding the application for each environment. Spring Boot externalises configuration so one artifact runs everywhere.
Reading Properties
application.properties:
app.name=Shop API
app.max-items=50
spring.datasource.url=jdbc:mysql://localhost:3306/shop
Inject a single value:
@Value("${app.max-items}")
private int maxItems;
Better — bind a whole group to a typed object:
@Component
@ConfigurationProperties(prefix = "app")
public class AppProperties {
private String name;
private int maxItems;
// getters and setters required for binding
}
This is validated at startup rather than failing at first use, and gives you IDE autocomplete.
Profiles
Keep one file per environment:
application.properties <- shared defaults
application-dev.properties <- laptop
application-prod.properties <- production
Activate one:
java -jar shop.jar --spring.profiles.active=prod
Profile-specific beans:
@Bean
@Profile("dev")
public DataSource h2InMemory() { ... }
@Bean
@Profile("prod")
public DataSource productionPool() { ... }
Precedence (highest wins)
- Command-line arguments
- Environment variables
application-{profile}.propertiesapplication.properties@Valuedefaults in code
This ordering is what lets a container platform override any setting without touching your jar.
Secrets
Never commit passwords. Read them from the environment:
spring.datasource.password=${DB_PASSWORD}
Spring resolves DB_PASSWORD from the environment, so the value never enters source control.
Common Mistakes
- Committing production secrets: Once pushed, treat the credential as compromised and rotate it.
- Typos in property names: A misspelled key is silently ignored.
@ConfigurationPropertiescatches this;@Valuedoes not. @Valueon a static field: Silently stays null. Spring injects instance fields only.- Forgetting to activate a profile: Without it, only
application.propertiesapplies — often pointing at localhost.
Best Practices
- Prefer
@ConfigurationPropertiesover scattered@Valueannotations. - Secrets from the environment or a vault, never from files in the repository.
- Keep defaults safe: If a profile is missing, the app should fail loudly rather than quietly hit production.
Practice Exercises
- The Two Profiles: Create
devandprodproperty files with differentapp.namevalues, then start the app under each and print the active one. - The Typed Binding: Convert three
@Valuefields into a single@ConfigurationPropertiesclass. - The Override Chain: Set the same property in the file, an environment variable, and a command-line argument. Confirm which wins.