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

Профили окружений

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

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

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

Why Profiles Exist

Real applications run in several environments — local, dev, staging, production — each needing different datasources, log levels, and feature toggles. Profiles let one codebase carry many configurations and activate the right set at runtime.

A profile is just a named label. Beans and property files can be tagged so they apply only when that profile is active.

Profile-Specific Property Files

Boot automatically loads application-{profile}.yml on top of the base application.yml. The profile file overrides matching keys while inheriting everything else.

# application.yml (base, always loaded)
spring:
  jpa:
    show-sql: false

# application-dev.yml (loaded when dev active)
spring:
  jpa:
    show-sql: true
  datasource:
    url: jdbc:h2:mem:devdb

Activating a Profile

Set spring.profiles.active to choose which profiles run. You can do this in a file, as an environment variable, or on the command line.

# Command line
java -jar app.jar --spring.profiles.active=prod

# Environment variable
export SPRING_PROFILES_ACTIVE=prod

# Multiple profiles
java -jar app.jar --spring.profiles.active=prod,metrics

Conditional Beans with @Profile

@Profile on a bean or configuration class makes it register only when that profile is active. This is ideal for swapping implementations between environments.

@Configuration
public class PaymentConfig {
    @Bean
    @Profile("prod")
    public PaymentGateway liveGateway() {
        return new StripeGateway();
    }

    @Bean
    @Profile("!prod")
    public PaymentGateway fakeGateway() {
        return new InMemoryGateway();
    }
}

Profile Expressions

The @Profile value supports simple logic: ! for NOT, & for AND, and | for OR. Group expressions with parentheses.

@Profile("!prod")                // anything except prod
@Profile("prod & metrics")       // both active
@Profile("dev | test")           // either active
@Profile("prod & (eu | us)")     // grouped

The Default Profile

When no profile is active, Spring enables the implicit default profile. You can target it explicitly with @Profile("default") for fallback beans used during plain local runs.

@Bean
@Profile("default")
public DataSeeder localSeeder() {
    return new SampleDataSeeder();
}

Profile Groups

A profile group bundles several profiles under one name, so activating the group activates them all. Great for composing cross-cutting concerns.

spring:
  profiles:
    group:
      production:
        - prod
        - metrics
        - swagger-off
# Now: --spring.profiles.active=production turns on all three

Including Profiles

spring.profiles.active sets the primary profiles, while spring.profiles.include adds extra ones unconditionally, regardless of which primary profile is selected.

spring:
  profiles:
    include:
      - common-logging
      - audit

Inspecting Active Profiles at Runtime

You can read active profiles from the Environment bean. This is useful for guard logic or for logging which configuration is live.

@Component
public class StartupLogger {
    private final Environment env;
    public StartupLogger(Environment env) { this.env = env; }

    @PostConstruct
    void log() {
        System.out.println("Active: "
            + String.join(",", env.getActiveProfiles()));
    }
}

Profiles in Tests

In integration tests, annotate the class with @ActiveProfiles to force a specific configuration, such as an in-memory database profile.

@SpringBootTest
@ActiveProfiles("test")
class OrderServiceTest {
    // loads application-test.yml + @Profile("test") beans
}

Common Pitfalls

Watch for these mistakes:

  • Forgetting to set spring.profiles.active in production, so dev defaults leak in
  • Putting secrets in application-dev.yml and committing it
  • Overusing @Profile where a simple property toggle would do

Quick Check

Test your grasp of profile expressions.

Recap

Profiles tailor one codebase to many environments.

  • application-{profile}.yml overrides base config
  • Activate via spring.profiles.active (file, env var, or CLI)
  • @Profile conditionally registers beans, with !, &, | expressions
  • Profile groups bundle related profiles
  • Use @ActiveProfiles in tests

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

Урок «Профили окружений» бесплатный?

Да — полный текст урока «Профили окружений» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 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 структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 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