Managing Application Profiles

1. Creating Profile-Specific Configurations

File Purpose
application.yml Base shared config
application-dev.yml Local development
application-staging.yml Staging env
application-prod.yml Production env

2. Activating Profiles (spring.profiles.active)

Mechanism Example
Property spring.profiles.active=prod
CLI --spring.profiles.active=prod
Env SPRING_PROFILES_ACTIVE=prod
JVM -Dspring.profiles.active=prod

3. Using Multiple Active Profiles

Example: Activate multiple profiles

java -jar app.jar --spring.profiles.active=prod,metrics,aws
Order Effect
Last wins Right-most profile overrides earlier ones for duplicate keys
All loaded All matching application-*.yml merged

4. Setting Default Profile (spring.profiles.default)

Property Description
spring.profiles.default Used only when no active profile set; defaults to default
@Profile("default") Active when no profile selected

5. Using @Profile Annotation on Beans

Example: Profile-bound bean

@Configuration
public class MailConfig {
  @Bean @Profile("prod")
  MailSender smtp() { return new SmtpMailSender(); }

  @Bean @Profile({"dev", "test"})
  MailSender mock() { return new InMemoryMailSender(); }
}

6. Using Profile Groups (spring.profiles.group)

Example: Profile groups for production and qa

spring:
  profiles:
    group:
      production: [prod, metrics, audit]
      qa: [test, h2, mock-mail]
Activate Result
--spring.profiles.active=production Loads prod, metrics, audit

7. Using Profile Expressions (!, &, |)

Expression Meaning
@Profile("!prod") NOT prod
@Profile("prod & aws") Both active
@Profile("prod | staging") Either active
@Profile("prod & !audit") Combinations

8. Loading Profile-Specific YAML Documents

Example: Multi-document YAML per profile

spring:
  application:
    name: app
---
spring:
  config:
    activate:
      on-profile: dev
server:
  port: 8081
---
spring:
  config:
    activate:
      on-profile: prod
server:
  port: 80

9. Detecting Active Profiles Programmatically

Example: Read active profiles from Environment

@Component
public class ProfilePrinter {
  public ProfilePrinter(Environment env) {
    String[] active = env.getActiveProfiles();
    boolean isProd = Arrays.asList(active).contains("prod");
  }
}
API Description
Environment.getActiveProfiles() Profiles activated
Environment.getDefaultProfiles() Default fallback
Environment.acceptsProfiles(Profiles.of("prod")) Expression check

10. Testing with Specific Profiles (@ActiveProfiles)

Example: Activate test profile

@SpringBootTest
@ActiveProfiles("test")
class OrderServiceTests { /* … */ }
Annotation Use
@ActiveProfiles("test") Activate profiles in test context
@ActiveProfiles(profiles={"test","h2"}, inheritProfiles=false) Replace inherited
ActiveProfilesResolver Programmatic resolution