Spring Profiles provide a flexible way to load environment-specific configurations in a Spring-based application. Here’s a step-by-step guide on how to use them:
Steps to Inject Environment-Specific Values Using Spring Profiles
- Define Profile-Specific Properties Files
Create separate property files for different environments (e.g., development, testing, production). Make sure to name them with a clear convention.Examples:
application-dev.properties
(for development)application-prod.properties
(for production)application-test.properties
(for testing)
In these files, define environment-specific values.
Example (application-dev.properties
):app.name=MyApp (Dev Environment) app.url=http://localhost:8080
Example (
application-prod.properties
):app.name=MyApp (Production) app.url=https://myapp.com
- Activate the Profile
Use one of the following methods to specify which profile is active:- In
application.properties
orapplication.yml
: Add thespring.profiles.active
property.
spring.profiles.active=dev
- As a Command-Line Argument:
You can pass the profile during application startup:
java -jar myapp.jar --spring.profiles.active=prod
- As an Environment Variable:
Set theSPRING_PROFILES_ACTIVE
environment variable:
export SPRING_PROFILES_ACTIVE=prod
- In
- Use the
@Profile
Annotation in Beans (Optional)
Annotate components or configurations that should only load in specific profiles using the@Profile
annotation.Example:
@Component @Profile("dev") public class DevDatabaseInitializer { public DevDatabaseInitializer() { System.out.println("Initializing Development Database..."); } }
The above bean will only be loaded when the “dev” profile is active.
-
Access Values from Properties Files
Use@Value
or the@ConfigurationProperties
annotation to inject values into your code.Example:
@Component public class AppConfig { @Value("${app.name}") private String appName; @Value("${app.url}") private String appUrl; public void printConfig() { System.out.println("App Name: " + appName); System.out.println("App URL: " + appUrl); } }
- (Optional) Use
application.yml
for Profile-Specific Configuration
Instead of multiple property files, you can use a singleapplication.yml
with profile-specific sections:spring: profiles: active: dev --- spring: profiles: dev app: name: MyApp (Dev Environment) url: http://localhost:8080 --- spring: profiles: prod app: name: MyApp (Production) url: https://myapp.com
Using Spring Profiles allows you to maintain clean and environment-specific configurations, reducing the chance of errors and simplifying the deployment process.