Spring 注释 conditionalOnBean 不起作用
我定义了一个带有注解配置的类
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);
}
}
MetricsFormatEndpoint 运行良好.
the MetricsFormatEndpoint works well.
但是我使用了注解conditionalOnBean,它根本不起作用.
but I use the annotation conditionalOnBean, it doesn't work at all.
@Bean
@ConditionalOnBean(MetricsEndpoint.class)
public MetricsFormatEndpoint metricsFormatEndpoint() {
return new MetricsFormatEndpoint(metricsEndpoint);
}
查看 localhost:8080/beans,spring applicationContext 有 bean '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":[]}
我看了注解@ConditionalOnBean 的文档,它说应该检查的bean 的类类型.当 {@link ApplicationContext} 中包含任何指定的类时,条件匹配.
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}.
谁能告诉我为什么
@ConditionalOnBean
的 javadoc 将其描述为:
The javadoc for @ConditionalOnBean
describes it as:
Conditional
仅当指定的 bean 类和/或名称已包含在 BeanFactory
中时才匹配.
Conditional
that only matches when the specified bean classes and/or names are already contained in theBeanFactory
.
在这种情况下,关键部分是已经包含在 BeanFactory
中".在任何自动配置类之前考虑您自己的配置类.这意味着 MetricsEndpoint
bean 的自动配置尚未在您自己的配置检查其存在时发生,因此,您的 MetricsFormatEndpoint
bean未创建.
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.
一种方法是 为您的 MetricsFormatEndpoint
bean 创建您自己的自动配置类,并使用 @AutoConfigureAfter(EndpointAutoConfiguration.class)
对其进行注释.这将确保在定义 MetricsEndpoint
bean 之后评估其条件.
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.