Explain how Spring Boot profiles work.

Spring Boot Profiles provide a mechanism to load different configurations and beans based on the environment in which the application is running. They help developers maintain separate settings for development, testing, staging, and production without changing the application code.

Key Points: • Profiles allow environment-specific configurations using a single codebase. • Only the beans and properties associated with the active profile are loaded. • 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

Instead of modifying code for each environment, Spring Boot automatically loads the appropriate configuration based on the active profile.

Code Example:

application-dev.properties

server.port=8080
spring.datasource.url=

jdbc:h2:mem:testdb

application-prod.properties

server.port=9090
spring.datasource.url=

jdbc:postgresql://localhost/proddb

Activate Profile:

application.properties

spring.profiles.active=dev

Profile-Specific Bean:

@Service
@Profile("dev")
public class MockPaymentService
        implements PaymentService {
}

@Service
@Profile("prod")
public class RealPaymentService
        implements PaymentService {
}

When the "dev" profile is active: • MockPaymentService is loaded.

When the "prod" profile is active: • RealPaymentService is loaded.

Ways to Activate a Profile:

1. application.properties

spring.profiles.active=prod

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

Benefits: • Environment-specific configuration management. • No code changes between environments. • Easier deployment and maintenance. • Better security by separating sensitive configurations. • Supports multiple deployment environments efficiently.

Real-World Example:

Development: • Local database • Debug logging enabled

Testing: • Test database • Additional validation

Production: • Production database • Optimized logging • Security configurations enabled

Spring Boot automatically loads the appropriate configuration based on the active profile.

Interview Tip: A concise interview answer is: Spring Boot Profiles allow environment-specific configurations by loading only the beans and properties associated with the active profile. They are commonly used to maintain separate settings for development, testing, and production environments and can be activated using configuration files, command-line arguments, JVM parameters, or environment variables.