0Pricing
Spring Boot 4 Microservices & REST APIs · Aula

application.properties e YAML

Configure aplicativos com arquivos de propriedades e YAML.

application.properties e YAML é uma aula grátis de Spring Boot 4 Microservices & REST APIs no CoddyKit. Esta é a aula 1 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.

Where Configuration Lives

Spring Boot reads externalized configuration from application.properties or application.yml, placed under src/main/resources. This keeps tunable values out of your compiled code.

At startup Boot loads these files into the Environment, making every key available for injection, conditional beans, and auto-configuration.

  • One file for the whole app, or split per profile
  • Values can be overridden later by env vars or CLI args

The .properties Format

The classic format is a flat list of key=value lines. Nested concepts are expressed with dotted keys.

It is simple and diff-friendly, but verbose when you have deep structures because each key repeats the full path.

server.port=8080
server.servlet.context-path=/api
spring.datasource.url=jdbc:postgresql://localhost:5432/app
spring.datasource.username=app_user
spring.jpa.hibernate.ddl-auto=validate

The YAML Format

application.yml expresses the same data as a hierarchy, so shared prefixes are written once. It is easier to read for deeply nested config like spring.jpa.properties.hibernate.*.

Indentation is significant: use spaces, never tabs, and keep two spaces per level.

server:
  port: 8080
  servlet:
    context-path: /api
spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/app
    username: app_user
  jpa:
    hibernate:
      ddl-auto: validate

Lists and Maps in YAML

YAML shines for collections. A sequence uses - items; a map is just nested keys. Spring binds these directly to List and Map properties.

app:
  cors:
    allowed-origins:
      - https://app.example.com
      - https://admin.example.com
  feature-flags:
    beta-search: true
    dark-mode: false

Referencing Other Properties

You can interpolate one property into another with ${...}. This avoids repeating literals and lets a single base value drive several derived keys.

app:
  name: orders-service
  base-url: https://api.example.com
  health-url: ${app.base-url}/actuator/health
logging:
  file:
    name: /var/log/${app.name}.log

Default Values with Placeholders

Inside a placeholder you can supply a fallback after a colon: ${KEY:default}. Spring uses the default when the referenced property or environment variable is absent.

app:
  timeout-ms: ${REQUEST_TIMEOUT:5000}
  region: ${AWS_REGION:eu-central-1}

Injecting Single Values with @Value

For one-off properties, inject directly with @Value. SpEL placeholders resolve against the Environment at bean creation time.

Use @Value for a handful of keys; prefer @ConfigurationProperties when a feature has many related settings.

@Service
public class OrderService {
    @Value("${app.timeout-ms:5000}")
    private long timeoutMs;

    @Value("${app.name}")
    private String appName;
}

Properties vs YAML: Trade-offs

Functionally they are interchangeable; the choice is about ergonomics.

  • .properties — trivial parsing, great for small/flat config, no indentation traps
  • .yml — concise for nested trees, native lists/maps, but indentation-sensitive

If both files exist, .properties takes precedence over .yml for the same key, which can surprise teams. Pick one convention.

Multiple Documents in One YAML

A single YAML file can hold several documents separated by ---. Combined with spring.config.activate.on-profile, this lets you keep common and profile-specific values together.

spring:
  application:
    name: orders
---
spring:
  config:
    activate:
      on-profile: dev
  datasource:
    url: jdbc:h2:mem:devdb

Type Conversion and Durations

Spring converts string values into rich types. Duration accepts suffixes like 30s or 5m, and DataSize accepts 10MB. Enums and List are also converted automatically.

app:
  cache-ttl: 30m
  max-upload: 10MB
  log-level: WARN

Where Not to Put Secrets

Checked-in application.yml is the wrong home for passwords and API keys. Keep secrets in environment variables, a vault, or a secrets manager, and reference them via placeholders.

  • Commit non-sensitive defaults only
  • Inject secrets at deploy time

Quick Check

Test your understanding of property precedence.

Recap

You learned how Spring Boot externalizes configuration.

  • application.properties and application.yml both feed the Environment
  • YAML is concise for nested trees and native lists/maps
  • Use ${...} for references and ${KEY:default} for fallbacks
  • Spring converts to types like Duration and DataSize
  • Keep secrets out of committed files

Perguntas Frequentes

A aula “application.properties e YAML” é grátis?

Sim — o texto completo de “application.properties e YAML” é 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 “application.properties e YAML”?

Configure aplicativos com arquivos de propriedades e YAML. 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 1 de 4.

Quanto tempo leva a aula “application.properties e YAML”?

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

  1. application.properties e YAML
  2. Perfis para ambientes
  3. Configuração segura quanto a tipos com @ConfigurationProperties
  4. Configuração externa e substituível
← Voltar para Spring Boot 4 Microservices & REST APIs