Configuração externa e substituível
Substitua a configuração pelo ambiente e pela linha de comando.
Configuração externa e substituível é uma aula grátis de Spring Boot 4 Microservices & REST APIs no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Spring Boot 4 Microservices & REST APIs, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Spring Boot 4 Microservices & REST APIs inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
The 12-Factor Idea
A core principle of portable apps is storing configuration in the environment, not in code. The same artifact should run anywhere, with behavior changed only by external config.
Spring Boot embraces this: a single jar reads from many sources and merges them with a well-defined precedence.
Many Sources, One Environment
Boot collects configuration from numerous property sources — files, environment variables, command-line args, and more — into one unified Environment.
- Each source contributes key/value pairs
- Higher-priority sources win on conflicts
- Your code never knows or cares where a value came from
Precedence Order (High to Low)
When the same key appears in several sources, the highest-priority source wins. A simplified, commonly used ordering:
- Command-line arguments
- OS environment variables
- Profile-specific
application-{profile}files - Base
applicationfiles - Defaults in code /
@Valuefallbacks
This is why a CLI flag can override anything baked into the jar.
Overriding with Command-Line Args
Pass --key=value after the jar. These have very high precedence and are ideal for one-off overrides or container entrypoints.
java -jar app.jar \
--server.port=9090 \
--spring.profiles.active=prod \
--app.mail.host=smtp.prod.example.comOverriding with Environment Variables
Environment variables use an UPPER_SNAKE_CASE form of the property name: dots and dashes become underscores. This is the standard way to inject config in containers.
# property: app.mail.host
export APP_MAIL_HOST=smtp.prod.example.com
# property: server.port
export SERVER_PORT=9090
# property: spring.datasource.password
export SPRING_DATASOURCE_PASSWORD=s3cretRelaxed Binding for Env Vars
Because env var names are constrained, Spring maps them back to canonical property names. APP_MAIL_MAX_RETRIES resolves to app.mail.maxRetries. This lets you set any property from the environment.
Injecting Secrets at Deploy Time
Keep secrets out of the jar; reference them with placeholders and let the platform supply real values via env vars. The committed file holds only a safe default or none.
spring:
datasource:
url: ${DB_URL}
username: ${DB_USER:app}
password: ${DB_PASSWORD}External Config Files
Point Boot at config outside the jar with spring.config.location or add extra files with spring.config.additional-location. Operators can drop a file next to the deployment without rebuilding.
java -jar app.jar \
--spring.config.additional-location=file:/etc/myapp/Importing Config
Modern Boot supports spring.config.import to pull in extra documents, optional files, or even config server entries, merged with the normal precedence rules.
spring:
config:
import:
- optional:file:/etc/myapp/override.yml
- configserver:Random Values
The random property source generates values on demand — handy for test data or ephemeral identifiers, though not for stable secrets.
app:
instance-id: ${random.uuid}
jitter-ms: ${random.int(0,500)}Debugging Where a Value Came From
When a value is not what you expect, inspect the merged Environment. The actuator /env endpoint lists every property source and the winning value, making precedence problems easy to diagnose.
# requires spring-boot-starter-actuator + exposure
GET /actuator/env/server.portQuick Check
Test your understanding of precedence.
Recap
Externalized config makes one artifact run everywhere.
- Many sources merge into one
Environmentby precedence - CLI args > env vars > profile files > base files > code defaults
- Env vars use UPPER_SNAKE_CASE relaxed binding
- Inject secrets via placeholders at deploy time
- Use
/actuator/envto debug where a value originated
Perguntas Frequentes
A aula “Configuração externa e substituível” é grátis?
Sim — o texto completo de “Configuração externa e substituível” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Spring Boot 4 Microservices & REST APIs, atualize para CoddyKit PRO. O curso de Spring Boot 4 Microservices & REST APIs inclui 4 aulas no total.
O que vou aprender em “Configuração externa e substituível”?
Substitua a configuração pelo ambiente e pela linha de comando. Você pratica Spring Boot 4 Microservices & REST APIs com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Spring Boot 4 Microservices & REST APIs?
Nenhuma experiência prévia é necessária. Spring Boot 4 Microservices & REST APIs no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Configuração externa e substituível”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Spring Boot 4 Microservices & REST APIs?
Sim. Cada aula de Spring Boot 4 Microservices & REST APIs inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- application.properties e YAML
- Perfis para ambientes
- Configuração segura quanto a tipos com @ConfigurationProperties
- Configuração externa e substituível