Spring annotation conditionalOnBean not working

拜拜、爱过 提交于 2020-01-23 05:37:09

问题


I defined a class with annotation Configuration

    @Configuration
    @AutoConfigureAfter(EndpointAutoConfiguration.class)
    public class EndpointConfiguration {
        @Resource
        private MetricsEndpoint metricsEndpoint;

        @Bean
        public MetricsFormatEndpoint metricsFormatEndpoint() {
            return new MetricsFormatEndpoint(metricsEndpoint);
        }
    }

the MetricsFormatEndpoint works well.

but I use the annotation conditionalOnBean, it doesn't work at all.

    @Bean
    @ConditionalOnBean(MetricsEndpoint.class)
    public MetricsFormatEndpoint metricsFormatEndpoint() {
        return new MetricsFormatEndpoint(metricsEndpoint);
    }

see the localhost:8080/beans,the spring applicationContext has the bean 'metricsEndpoint',

    {"bean":"metricsEndpoint","scope":"singleton",
     "type":"org.springframework.boot.actuate.endpoint.MetricsEndpoint",
     "resource":"class path resource 
    [org/springframework/boot/actuate/autoconfigure/EndpointAutoConfiguration.class]",
    "dependencies":[]}

I read the document of the annotation @ConditionalOnBean, it says The class type of bean that should be checked. The condition matches when any of the classes specified is contained in the {@link ApplicationContext}.

who can tell me why


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/31799855/spring-annotation-conditionalonbean-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!