Why Use Profiles?

Profiles in Spring Boot allow an application to load different configurations for different environments such as development, testing, staging, and production. This helps maintain a single codebase while using environment-specific settings and resources.

Key Points: • Profiles separate environment-specific configurations without changing application code. • They simplify deployment across development, testing, and production environments. • Profiles improve maintainability and reduce configuration errors.

Example: Consider a Spring Boot application with different database configurations:

Development Environment: • Local MySQL Database • Debug Logging Enabled

Testing Environment: • In-Memory H2 Database • Mock External Services

Production Environment: • Production Database Cluster • Optimized Logging Configuration

The same application code runs in all environments while only the configuration changes.

Configuration Example:

application-dev.properties
application-test.properties
application-prod.properties

Activating a profile:

spring.profiles.active=prod

Or using command line:

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

Using Profile-Specific Beans:

@Profile("dev")
@Bean
public DataSource devDataSource() {
    return new H2DataSource();
}

@Profile("prod")
@Bean
public DataSource prodDataSource() {
    return new MysqlDataSource();
}

Benefits of Using Profiles:

• Environment-specific configurations. • Easier deployment management. • Reduced risk of production configuration mistakes. • Improved flexibility and maintainability.

Real-World Example:

An e-commerce application uses:

Development: • Local database • Mock payment gateway

Production: • Production database • Real payment gateway integration

The application behavior changes automatically based on the active profile.

Interview Tip: A concise interview answer is: Spring Profiles allow us to maintain different configurations for different environments such as development, testing, and production without modifying application code. This improves flexibility, simplifies deployment, and helps manage environment-specific resources efficiently.