Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

195
Views
How do you get current active/default Environment profile programmatically in Spring?

I need to code different logic based on different current Environment profile.

How can you get the currently active and default profiles from Spring?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

You can auto connect the Environment

 @Autowired Environment env;

Environment offers:

  • String[] getActiveProfiles() ,
  • String[] getDefaultProfiles() , and
  • boolean acceptsProfiles(String... profiles)
over 4 years ago · Santiago Trujillo Report

0

Expanding on User1648825's nice and simple answer:

 @Value("${spring.profiles.active}") private String activeProfile;

This can throw an IllegalArgumentException if no profiles are set (I get null). This can be a good thing if you need to configure it; if not, use the 'default' syntax for @Value, ie:

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

...activeProfile now contains 'Unknown' if spring.profiles.active could not be resolved

over 4 years ago · Santiago Trujillo Report

0

Here is a more complete example.

Autowire Environment

First you will want to autowire the environment bean.

@Autowired
private Environment environment;

Check if Profiles exist in Active Profiles

Then you can use getActiveProfiles() to find out if the profile exists in the list of active profiles. Here is an example that takes the String[] from getActiveProfiles(), gets a stream from that array, then uses matchers to check for multiple profiles(Case-Insensitive) which returns a boolean if they exist.

//Check if Active profiles contains "local" or "test"
if(Arrays.stream(environment.getActiveProfiles()).anyMatch(
   env -> (env.equalsIgnoreCase("test") 
   || env.equalsIgnoreCase("local")) )) 
{
   doSomethingForLocalOrTest();
}
//Check if Active profiles contains "prod"
else if(Arrays.stream(environment.getActiveProfiles()).anyMatch(
   env -> (env.equalsIgnoreCase("prod")) )) 
{
   doSomethingForProd();
}

You can also achieve similar functionality using the annotation @Profile("local") Profiles allow for selective configuration based on a passed-in or environment parameter. Here is more information on this technique: Spring Profiles

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!