0Pricing
Spring Boot 4 Microservices & REST APIs · Урок

Внешняя конфигурация и её переопределение

Переопределяйте конфигурацию через окружение и командную строку

«Внешняя конфигурация и её переопределение» — бесплатный урок Spring Boot 4 Microservices & REST APIs на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Spring Boot 4 Microservices & REST APIs, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Spring Boot 4 Microservices & REST APIs содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

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 application files
  • Defaults in code / @Value fallbacks

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.com

Overriding 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=s3cret

Relaxed 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.port

Quick Check

Test your understanding of precedence.

Recap

Externalized config makes one artifact run everywhere.

  • Many sources merge into one Environment by 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/env to debug where a value originated

Часто задаваемые вопросы

Урок «Внешняя конфигурация и её переопределение» бесплатный?

Да — полный текст урока «Внешняя конфигурация и её переопределение» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Spring Boot 4 Microservices & REST APIs, подпишись на CoddyKit PRO. Курс Spring Boot 4 Microservices & REST APIs содержит 4 уроков всего.

Чему я научусь в уроке «Внешняя конфигурация и её переопределение»?

Переопределяйте конфигурацию через окружение и командную строку Ты практикуешь Spring Boot 4 Microservices & REST APIs с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Spring Boot 4 Microservices & REST APIs?

Предыдущий опыт не требуется. Spring Boot 4 Microservices & REST APIs на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Внешняя конфигурация и её переопределение»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Spring Boot 4 Microservices & REST APIs?

Да. Каждый урок Spring Boot 4 Microservices & REST APIs включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. application.properties и YAML
  2. Профили окружений
  3. Типобезопасная конфигурация с @ConfigurationProperties
  4. Внешняя конфигурация и её переопределение
← Назад к Spring Boot 4 Microservices & REST APIs