在 Condition 或 ConfigurationCondition 中使用上下文 bean

Arn*_*lle 7 spring spring-boot

我希望使用 org.springframework.context.annotation.Condition 接口在启动时禁用/启用我的一些 @Configuration 类。下面的例子:

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
}
Run Code Online (Sandbox Code Playgroud)

我这里遇到的问题是条件在实例化任何上下文之前执行,然后“DocConf”还不存在。如果我读取环境变量或类似的内容,则条件效果很好。

那么,是否可以基于上下文的 spring bean 使用这种条件?

tkr*_*use 4

这是不可能的,因为您的 DocConf 类没有作为配置加载,@Bean 注释的 bean 是在所有配置完成后创建的。

为此,您的 DocConf 类必须作为 Spring 配置添加到上下文中,因此通过来自不同配置的 @Bean 包含它是行不通的,因为非配置 Bean 仅在配置阶段之后创建。

考虑这篇文章:http://www.javarticles.com/2016/01/spring-configuration-condition-example.html

另一个例子在 http://javapapers.com/spring/spring-conditional-annotation/