Profile-based configuration helps you run your app with different settings for different situations, like development or production. It keeps your app flexible and easy to manage.
0
0
Profile-based configuration in Spring Boot
Introduction
When you want different database settings for testing and live use.
When you need to enable debug logging only during development.
When deploying the same app to multiple environments with different URLs or keys.
When you want to turn features on or off depending on the environment.
Syntax
Spring Boot
spring.profiles.active=profileName # Example: application-dev.properties server.port=8081 # Example: application-prod.properties server.port=80
Use
spring.profiles.active in application.properties or as a command line argument to select the active profile.Create separate
application-{profile}.properties files for each profile's settings.Examples
This sets the active profile to dev. Spring Boot will load
application-dev.properties settings.Spring Boot
# application.properties
spring.profiles.active=devSettings used only when the dev profile is active.
Spring Boot
# application-dev.properties server.port=8081 logging.level.root=DEBUG
Settings used only when the prod profile is active.
Spring Boot
# application-prod.properties server.port=80 logging.level.root=ERROR
Run the app with the prod profile from the command line.
Spring Boot
# Command line
java -jar app.jar --spring.profiles.active=prodSample Program
This Spring Boot app reads a message from configuration based on the active profile and shows it at the home URL.
Create two files:
application-dev.propertieswithapp.message=Hello from Development!application-prod.propertieswithapp.message=Welcome to Production!
Set the active profile to dev or prod to see different messages.
Spring Boot
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } @RestController class HelloController { @Value("${app.message}") private String message; @GetMapping("/") public String home() { return message; } }
OutputSuccess
Important Notes
You can activate multiple profiles by separating them with commas, like spring.profiles.active=dev,debug.
Profiles help keep sensitive info like passwords out of your main config.
Use @Profile annotation on beans to load them only for certain profiles.
Summary
Profiles let you switch app settings easily for different environments.
Create separate config files named application-{profile}.properties.
Activate profiles via properties file, command line, or environment variables.