Using context beans within a Condition or a ConfigurationCondition

Viewed 1786

I wish to use a org.springframework.context.annotation.Condition interface to disable/enable at startup some of my @Configuration classes. Example below:

public class Condition implements ConfigurationCondition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        //Gets the configuration manager from the context
        RapidConfDocConfiguration.DocConf docConf = context.getBeanFactory().getBean(DocConf.class);

        return docConf.isEnabled();
    }
}

@Configuration
public class ConfDocConfiguration {

    @Bean
    public DocConf docConf() {
        return new DocConf(true);
    }
}

@Configuration
@Import(ConfDocConfiguration.class)
@Conditional({Condition.class})
public class RapidSwaggerConfiguration {
    //Some configurations
}

The problem i have here is that the Condition is executed before that any of the context is instantiated and then the 'DocConf' is not yet present. The Condition works well if i read an environment variable or something like that.

So, is it possible to use this kind of condition based on a spring bean of the context ?

1 Answers

This is not possible because your DocConf class is not loaded as a Configuration, @Bean annotated beans are created after all configuration is done.

For this to work, your DocConf class would have to be added to the context as a Spring configuration, so including it via @Bean from a different configuration cannot work, because non-configuration Beans are only created after the configuration phase.

Consider this article: http://www.javarticles.com/2016/01/spring-configuration-condition-example.html

Another example at http://javapapers.com/spring/spring-conditional-annotation/

Related