Spring / Spring Boot 4 Basics Interview Questions
What are Spring Boot profiles and how do you use them for environment-specific configuration?
Profiles allow different configuration to be activated based on the deployment environment (dev, test, staging, prod). Spring Boot supports profile-specific property files, conditional bean registration, and profile activation via environment variables.
# src/main/resources/application.yml (base config, always loaded) spring: application: name: order-service # src/main/resources/application-dev.yml (loaded only in "dev" profile) spring: datasource: url: jdbc:h2:mem:devdb driver-class-name: org.h2.Driver logging: level: root: DEBUG # src/main/resources/application-prod.yml (loaded only in "prod" profile) spring: datasource: url: jdbc:postgresql://prod-db:5432/orders username: ${DB_USER} password: ${DB_PASSWORD} logging: level: root: WARN # Activate a profile: # 1. Environment variable: export SPRING_PROFILES_ACTIVE=prod # 2. JVM argument: -Dspring.profiles.active=prod # 3. application.properties: # spring.profiles.active=dev // Profile-conditional bean registration: @Configuration public class CacheConfig { @Bean @Profile("dev") // Only in dev: simple in-memory cache public CacheManager devCache() { return new ConcurrentMapCacheManager(); } @Bean @Profile("prod") // Only in prod: Redis cache public CacheManager prodCache(RedisConnectionFactory factory) { return RedisCacheManager.create(factory); } } // Multi-profile documents in single yml file (using --- separator): # application.yml: spring: config: activate: on-profile: test datasource: url: jdbc:h2:mem:testdb
More Related questions...