Sobes.tech
Junior — Middle

How can different configuration profiles be implemented in Spring?

sobes.tech AI

Answer from AI

In Spring, the ability to use different configuration profiles is implemented using the Spring Profiles mechanism. This allows defining different settings and beans for various environments (e.g., dev, test, prod).

How to do this:

  1. Define profiles in configuration files

You can create multiple files like application-{profile}.properties or application-{profile}.yml, for example:

  • application-dev.properties
  • application-prod.properties
  1. Annotate beans with profile indication
@Configuration
@Profile("dev")
public class DevConfig {
    // beans for dev
}

@Configuration
@Profile("prod")
public class ProdConfig {
    // beans for prod
}
  1. Activate the profile

The profile can be activated via:

  • Command line parameter: -Dspring.profiles.active=dev
  • In application.properties: spring.profiles.active=dev
  • Through environment variables

Thus, Spring loads only those beans and settings that correspond to the active profile, which makes managing configuration for different environments convenient.