File config externalize settings ra ngoài code — environment-specific values (DB URL, port, log level...) thay đổi không cần rebuild.
Hai format:
# application.properties
server.port=8080
spring.datasource.url=jdbc:postgresql://localhost/db# application.yml — hierarchical, cleaner cho nested config
server:
port: 8080
spring:
datasource:
url: jdbc:postgresql://localhost/dbTruy cập trong code:
@Value("${server.port}")
private int port;
// Recommended — typed binding
@ConfigurationProperties(prefix = "app")
record AppProps(String name, int maxRetries) {}Profiles: application-dev.yml, application-prod.yml → activate qua spring.profiles.active=prod. Deploy 1 JAR cho mọi env.
Thứ tự ưu tiên (cao → thấp): command-line args → env vars → application-{profile}.yml → application.yml. Override dễ ngoài JAR mà không sửa source.
Secrets không nên commit: dùng env vars, Vault, AWS Secrets Manager, hoặc Spring Cloud Config server.
Config files externalize settings outside code — environment-specific values (DB URLs, ports, logging) change without rebuilding.
Two formats:
# application.properties
server.port=8080
spring.datasource.url=jdbc:postgresql://localhost/db# application.yml — hierarchical, cleaner for nested config
server:
port: 8080
spring:
datasource:
url: jdbc:postgresql://localhost/dbReading them in code:
@Value("${server.port}")
private int port;
// Recommended — typed binding
@ConfigurationProperties(prefix = "app")
record AppProps(String name, int maxRetries) {}Profiles: application-dev.yml, application-prod.yml → activate via spring.profiles.active=prod. Deploy a single JAR across environments.
Precedence (highest → lowest): command-line args → env vars → application-{profile}.yml → application.yml. Easy to override outside the JAR without changing source.
Secrets should not be committed: use env vars, Vault, AWS Secrets Manager, or Spring Cloud Config server.