What are Spring Profiles and how do you use them?

Spring Profiles are a feature that allows different configurations and beans to be loaded for different environments such as Development, Testing, and Production. They help manage environment-specific settings without changing the application code.

Key Points: • Profiles enable environment-specific bean configuration and property management. • The @Profile annotation is used to associate a bean or configuration class with a specific profile. • Common profiles include dev, test, and prod. • Only the beans belonging to the active profile are loaded into the Spring container. • Profiles can be activated using application.properties, JVM arguments, environment variables, or programmatically.

Example: A development environment may use an in-memory database, while a production environment uses a MySQL or PostgreSQL database. Spring Profiles allow the appropriate configuration to be loaded automatically.

Code Example:

@Configuration
@Profile("dev")
public class DevConfig {
}

@Configuration
@Profile("prod")
public class ProdConfig {
}

application.properties

spring.profiles.active=dev

Interview Tip: A concise interview answer is:

"Spring Profiles are used to manage environment-specific configurations. By using the @Profile annotation, we can define different beans and settings for environments such as development, testing, and production, and Spring loads only the configuration associated with the active profile."