- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我遇到了奇怪的情况。我正在尝试编写自动配置类,如果另一个 bean 存在或不存在,我会在其中创建 bean,因此我对 bean 有条件,并且对相同类型的缺少 bean 有条件。
这是我的代码:
@Bean
@ConditionalOnMissingBean(
type = {"com.example.Api"}
)
public ApiManager apiManager() {
return new ApiManager() {
public Result getValue(Request request) {
throw new Exception("Api not provided.");
}
public Result setValue(Request request) {
throw new Exception("Api not provided.");
}
};
}
@Bean
@ConditionalOnBean(
type = {"com.example.Api"}
)
public ApiManager apiManager(Api api) {
return new ApiManagerImpl(api);
}
问题是,如果它已经在@ConditionalOnMissingBean
中检查了com.example.Api
类型的bean,它就不会检查@ConditionalOnBean
没有丢失,则不会创建 bean。
我收到如下错误:
Parameter 2 of constructor in com.example.ServiceImpl required a bean of type 'com.example.ApiManager' that could not be found.
- Bean method 'apiManager' in 'ApiAutoConfiguration' not loaded because @ConditionalOnMissingBean (types: com.example.Api; SearchStrategy: all) found bean 'api'
- Bean method 'apiManager' in 'ApiAutoConfiguration' not loaded because @ConditionalOnMissingBean (types: com.example.Api; SearchStrategy: all) found bean 'api'
最佳答案
你得到的结果是非常合乎逻辑的。条件按顺序评估,这就是为什么在用户配置之后处理自动配置的原因。
如果上下文符合您的预期,我们必须在执行任何操作之前评估所有 bean 定义的所有条件。这将违背自动配置处理用户(用户配置)或自动配置提供的某种类型的 bean 的目的。
您需要重写此自动配置才能按顺序导入内容。一种方法是将每个方法移动到包私有(private)配置类上,然后执行以下操作:
@Configuration
@Import({ApiPresentConfiguration.class, ApiNotPresentConfiguration.class})
处理这个问题的更好方法是根本不这样做,而简单地使用 ObjectProvider
:
@Bean
public ApiManager apiManager(ObjectProvider<Api> api) {
// Check if API is present and then return the appropriate implementation
}
关于java - @ConditionalOnMissingBean 和 @ConditionalOnBean 位于同一类型上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55594600/
我在配置文件中定义了多个数据源 bean。我有 2 个名为 customerDataSource 的 bean。我希望仅在未加载其他 bean 时才实例化其中之一。我尝试使用 @Conditional
我正在使用 Spring Boot 2.1.6.RELEASE,我想知道应该如何使用 @ConditionalOnMissingBean ? 配置示例: @Configuration public c
所以我有一个标准的 Spring Boot Web 应用程序。我需要允许多种身份验证机制。所以我希望能够拥有处理不同身份验证的 jar 文件。一个用于 SAML 服务器、CAS、OAuth 等...
我有一个接口(interface)的两个实现 - default 和 dev。我将 @ConditionalOnProperty 用于默认实现,将 @Profile 和 @ConditionalOnM
我想使用 @ConditionalOnMissingBean 启用自定义配置和合理的默认值?我有一个 spring boot 应用程序: @Configuration @Import({CustomC
有没有办法让这两个 bean 实例化: @Bean @ConditionalOnMissingBean public Container bookContainer() { return ne
我遇到了奇怪的情况。我正在尝试编写自动配置类,如果另一个 bean 存在或不存在,我会在其中创建 bean,因此我对 bean 有条件,并且对相同类型的缺少 bean 有条件。 这是我的代码: @Be
我正在尝试启动一个已使用此注释的 springboot 应用程序。当我尝试启动应用程序时,出现以下错误: org.springframework.boot.autoconfigure.conditio
我正在使用 Spring Boot Starter 版本 2.0.8.RELEASE 并尝试升级到:2.1.4.RELEASE。我收到以下错误: The bean 'defaultKafkaStrea
我是一名优秀的程序员,十分优秀!