Search code examples
spring-bootautowiredspring-profiles

Conditional auto-wiring in Spring boot application


I have a spring boot application for which I want to create separate profiles for external and embedded tomcat. How can I check in my method which profile is active so that I can run the code based on particular profile. I came up with some code as shown below.

if("${spring.active.profile}".contains("external_tomcat_profile")) {
            //do something; 
 }else{
            //another thing;
        }

The above code does not work. How can I implement this functionality? or Is there and better way of doing this? And I am using two profiles one "test" for testing and another either embedded or external tomcat, so is it correct to use this condition

if("${spring.active.profile}".contains("external_tomcat_profile"))

Solution

  • You can use the Environment bean for that

    @Autowired
    Environment env;
    
    public void aMethod() {
       String[] activeProfiles = env.getActiveProfiles();
    }