My personal website.

Profiles in Spring


Profiles in Spring

In Spring, profiles provide a way to separate application configurations for different environments or use cases. They help you manage and organize configuration settings depending on the runtime environment or specific application requirements. You can activate profiles programmatically, through environment variables, or via command-line arguments.

Profiles help you manage environment-specific configurations, such as database connections, logging settings, or feature toggles, without modifying the source code.

Here’s how profiles work in Spring:

Defining profiles

Profiles can be defined in various configuration sources like application.properties, application.yml, or @Configuration classes.

In a properties file, you can define profile-specific properties by appending the profile name to the file name, like application-dev.properties or application-prod.properties.

In a YAML file, you can use the spring.profiles property to define profile-specific configurations:

spring:
  profiles: dev
logging:
  level:
    root: DEBUG

---
spring:
  profiles: prod
logging:
  level:
    root: WARN

In a @Configuration class, you can use the @Profile annotation to activate the configuration class only when a specific profile is active:

@Configuration
@Profile("dev")
public class DevConfiguration {
    // Configuration for the "dev" profile
}

@Configuration
@Profile("prod")
public class ProdConfiguration {
    // Configuration for the "prod" profile
}

Activating profiles

You can activate a profile through various methods:

Profile precedence

When multiple profiles are active, Spring combines the configurations from all active profiles. If there are conflicts between property values in different profiles, the last profile specified in the spring.profiles.active property takes precedence.

By using profiles, you can maintain separate configurations for different environments or use cases, making it easier to switch between environments without modifying the application’s source code.