1. What are Spring Boot Profiles?
Spring Boot profiles allow you to group configuration settings for different environments and activate the one you need at runtime. This helps manage multiple environments without changing code.
For example:
dev
→ development environment settingstest
→ testing environment settingsprod
→ production environment settings
2. How to Define Profiles
You can define profiles in application.properties
or application.yml
files:
Option 1: Using application.properties
# Default properties
server.port=8080
spring.datasource.url=jdbc:h2:mem:testdb
# Profile-specific properties
# application-dev.properties
server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/devdb
# application-prod.properties
server.port=8082
spring.datasource.url=jdbc:mysql://localhost:3306/proddb
Option 2: Using application.yml
spring:
profiles:
active: dev # default profile
---
spring:
profiles: dev
server:
port: 8081
spring:
datasource:
url: jdbc:mysql://localhost:3306/devdb
---
spring:
profiles: prod
server:
port: 8082
spring:
datasource:
url: jdbc:mysql://localhost:3306/proddb
3. Activating Profiles
You can activate a profile in several ways:
- In
application.properties
orapplication.yml
:
spring.profiles.active=dev
- As a command-line argument:
java -jar myapp.jar --spring.profiles.active=prod
- As an environment variable:
export SPRING_PROFILES_ACTIVE=prod
4. Using Profiles in Code
You can use @Profile
to make beans conditional based on the active profile:
@Configuration
@Profile("dev")
public class DevConfig {
@Bean
public MyService myService() {
return new DevServiceImpl();
}
}
@Configuration
@Profile("prod")
public class ProdConfig {
@Bean
public MyService myService() {
return new ProdServiceImpl();
}
}
Only the beans for the active profile will be created.
5. Benefits
- Avoid hardcoding environment-specific values.
- Easily switch between environments.
- Keep code clean and modular.
- Useful for cloud deployments or CI/CD pipelines.