How to determine programmatically the current active profile using Spring boot
Retrieve the current active profile in Spring Boot by injecting the Environment
and using the getActiveProfiles()
method:
This smart line of code returns the first active profile or says "none" if no profiles are in the game.
Deep dive into profiles
Understanding the terrain
The Environment
in Spring is a treasure map revealing the runtime properties, including not only profiles, but also properties loaded from various corners of your app.
Dealing with a crowd of profiles
Multiple profiles can coexist in perfect harmony! To manage them, loop over the profiles like a DJ loops samples:
Defining tasks for profiles
The Spring Boot is smart and can perform different tasks depending on the @Profile
in charge:
Best practices: the do's and don'ts
- Don't tightly couple: Business logic and the active profile should see each other casually, not be "in a relationship".
- Do use your profiles for choosing external configuration, not for controlling the application's internal mood swings.
- In testing, use
@ActiveProfiles
to accessorize your tests with the right profiles.
There's more than one way to skin a cat
If autowiring Environment
feels like a bad culinary choice, serve up the active profiles directly with @Value
for a gourmet treat:
The active profile game plan
Handling "profile emergencies"
Enhance the durability of your code against the rough weather of invalid or missing profiles:
Conditional logic based on active profile
Trigger different code behaviors based on the active profile like a magician pulls rabbits out of hats:
Profile-specific properties files
Create a application-{profile}.properties
file for each active profile as if it's a profile's private diary, which can detail its unique configuration.
Was this article helpful?