application.properties и YAML
Настраивайте приложения с помощью файлов свойств и YAML
«application.properties и YAML» — бесплатный урок Spring Boot 4 Microservices & REST APIs на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Spring Boot 4 Microservices & REST APIs, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Spring Boot 4 Microservices & REST APIs содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
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=validateThe 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: validateLists 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: falseReferencing 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}.logDefault 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:devdbType 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: WARNWhere 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.propertiesandapplication.ymlboth 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
DurationandDataSize - Keep secrets out of committed files
Часто задаваемые вопросы
Урок «application.properties и YAML» бесплатный?
Да — полный текст урока «application.properties и YAML» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Spring Boot 4 Microservices & REST APIs, подпишись на CoddyKit PRO. Курс Spring Boot 4 Microservices & REST APIs содержит 4 уроков всего.
Чему я научусь в уроке «application.properties и YAML»?
Настраивайте приложения с помощью файлов свойств и YAML Ты практикуешь Spring Boot 4 Microservices & REST APIs с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Spring Boot 4 Microservices & REST APIs?
Предыдущий опыт не требуется. Spring Boot 4 Microservices & REST APIs на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.
Сколько времени занимает урок «application.properties и YAML»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Spring Boot 4 Microservices & REST APIs?
Да. Каждый урок Spring Boot 4 Microservices & REST APIs включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- application.properties и YAML
- Профили окружений
- Типобезопасная конфигурация с @ConfigurationProperties
- Внешняя конфигурация и её переопределение