What is Spring Profiles? How do you start an application with a certain profile?

Spring Profiles allow you to maintain different configurations for different environments such as Development, Testing, Staging, and Production. A profile ensures that only the beans and configurations relevant to a specific environment are loaded, making applications more flexible and easier to manage across deployments.

Key Points: • Profiles help separate environment-specific configurations without changing the application code. • Different beans, properties, and settings can be activated based on the selected profile. • Common profiles include dev, test, qa, staging, and prod.

Example: Consider an application that uses:

• H2 Database in Development • MySQL in Testing • PostgreSQL in Production

Using Spring Profiles, the appropriate database configuration is loaded automatically based on the active profile.

Code Example:

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

    @Bean
    public DataSource dataSource() {

        return new H2DataSource();
    }
}

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

    @Bean
    public DataSource dataSource() {

        return new PostgreSQLDataSource();
    }
}

Ways to Activate a Profile:

1. application.properties

spring.profiles.active=dev

2. Command Line

java -jar app.jar --spring.profiles.active=prod

3. JVM Argument

java -Dspring.profiles.active=prod -jar app.jar

4. Environment Variable

SPRING_PROFILES_ACTIVE=prod

5. Programmatically

SpringApplication app =
        new SpringApplication(
                Application.class);

app.setAdditionalProfiles(
        "prod");

app.run(args);

Profile-Specific Property Files:

application-dev.properties

server.port=8080
logging.level.root=DEBUG

application-prod.properties

server.port=9090
logging.level.root=ERROR

Spring automatically loads the file corresponding to the active profile.

Benefits: • Clean separation of environment configurations. • Simplifies deployment across multiple environments. • Avoids manual code changes for environment-specific settings. • Improves maintainability and security.

Interview Tip: A concise interview answer is: Spring Profiles allow environment-specific configurations by activating only the beans and properties required for a particular environment. A profile can be activated through application.properties, command-line arguments, JVM parameters, environment variables, or programmatically. This helps manage development, testing, and production configurations efficiently.