Spring annotation conditionalOnBean not working

前端 未结 2 583
慢半拍i
慢半拍i 2021-01-11 15:00

I defined a class with annotation Configuration

    @Configuration
    @AutoConfigureAfter(EndpointAutoConfiguration         


        
相关标签:
2条回答
  • 2021-01-11 15:25

    The javadoc for @ConditionalOnBean describes it as:

    Conditional that only matches when the specified bean classes and/or names are already contained in the BeanFactory.

    In this case, the key part is "already contained in the BeanFactory". Your own configuration classes are considered before any auto-configuration classes. This means that the auto-configuration of the MetricsEndpoint bean hasn't happened by the time that your own configuration is checking for its existence and, as a result, your MetricsFormatEndpoint bean isn't created.

    One approach to take would be to create your own auto-configuration class for your MetricsFormatEndpoint bean and annotate it with @AutoConfigureAfter(EndpointAutoConfiguration.class). That will ensure that its conditions are evaluated after the MetricsEndpoint bean has been defined.

    0 讨论(0)
  • 2021-01-11 15:28

    ConditionalOnClass worked as well.

    Javadoc said that AutoConfigureAfter should be applied after other specified auto-configuration classes.

    And ConditionalOnClass matches when the specified classes are on the classpath. I think it's properer

    0 讨论(0)
提交回复
热议问题