Environment-based profiles help your application use different settings for different places, like your computer or a live server. This keeps things organized and safe.
Environment-based profiles in Spring Boot
spring.profiles.active=profileName
# In application-profileName.properties or application-profileName.yml
property.key=valueProfiles are named sets of configuration you can switch between.
You activate a profile by setting spring.profiles.active in your main config or environment.
dev and prod. The app uses port 8081 in dev and port 80 in prod.# application.properties spring.profiles.active=dev # application-dev.properties server.port=8081 # application-prod.properties server.port=80
test profile sets logging to debug level.# application.yml spring: profiles: active: test # application-test.yml logging: level: root: DEBUG
# Activate profile via command line
java -jar app.jar --spring.profiles.active=prodThis Spring Boot app has two beans. One runs only if the dev profile is active, the other only if prod is active. When you run the app with --spring.profiles.active=dev, it prints the dev message. With prod, it prints the prod message.
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } @Component @Profile("dev") class DevBean { public DevBean() { System.out.println("Dev profile active: Using development settings."); } } @Component @Profile("prod") class ProdBean { public ProdBean() { System.out.println("Prod profile active: Using production settings."); } }
You can have multiple profiles active at once by separating them with commas.
Use profiles to keep secrets and environment differences out of your main code.
Check which profile is active by printing or logging spring.profiles.active.
Profiles let your app use different settings for different environments.
Activate profiles in config files or command line.
Use @Profile to run code only for certain profiles.