Explain Codes LogoExplain Codes Logo

How to determine programmatically the current active profile using Spring boot

java
spring-boot
environment
profiles
Anton ShumikhinbyAnton Shumikhin·Nov 23, 2024
TLDR

Retrieve the current active profile in Spring Boot by injecting the Environment and using the getActiveProfiles() method:

@Autowired private Environment env; public String getActiveProfile() { return Arrays.stream(env.getActiveProfiles()) .findFirst() .orElse("none"); // If there are no profiles, we don't play "profile roulette"! }

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:

for(String profile : env.getActiveProfiles()) { // Make some sweet tunes with each profile }

Defining tasks for profiles

The Spring Boot is smart and can perform different tasks depending on the @Profile in charge:

@Configuration @Profile("dev") public class DevConfiguration { // ... Coded in a comfy hoodie, perhaps? }

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:

@Value("${spring.profiles.active:None}") private String activeProfiles;

The active profile game plan

Handling "profile emergencies"

Enhance the durability of your code against the rough weather of invalid or missing profiles:

public String getRequiredActiveProfile() { String[] profiles = env.getActiveProfiles(); return profiles.length > 0 ? profiles[0] : throw new IllegalStateException("Oppsie, there's no captain on this ship!"); }

Conditional logic based on active profile

Trigger different code behaviors based on the active profile like a magician pulls rabbits out of hats:

if (Arrays.asList(env.getActiveProfiles()).contains("staging")) { // Perform magic trick when backstage (staging)! }

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.