Search code examples
springspring-java-configspring-profiles

How to make a bean configuration trigger only when two profiles are active


I have a bean that only should get created iff the two profiles "demo" and "local" both are active. What is the best way to achieve this in a java based Spring Configuration.

What I came up with so far is, creating beans like the following:

@Profile("demo")
@Bean("isDemoActive")
public Boolean isDemoActive(){ return true;}

And get those injected in the bean creating method and do a if condition on those beans.

Is there a nicer/easier way to do this kind of stuff?


Solution

  • Here's my suggestion, as per my comment above:

    import org.springframework.context.annotation.Condition;
    import org.springframework.context.annotation.ConditionContext;
    import org.springframework.core.type.AnnotatedTypeMetadata;
    
    public class DoubleProfilesCondition implements Condition {
        public boolean matches(ConditionContext context,AnnotatedTypeMetadata metadata) {
    
            String[] activeProfiles = context.getEnvironment().getActiveProfiles();
    
            int counter = 0;
            for (int i = 0; i < activeProfiles.length; i++) {
                String profile = activeProfiles[i];
                if (profile.equals("profile1") || profile.equals("profile2")) {
                    counter++;
                }
            }
    
            if (counter == 2)
                return true;
            return false;
       }
    }
    

    And the class that dictates which beans are created:

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Conditional;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    @Conditional(DoubleProfilesCondition.class)
    public class MyConfig {
    
        public @Bean
        ExampleService service() {
            ExampleService service = new ExampleService();
            service.setMessage("hello, success!");
            return service;
        }
    }