【问题标题】:How to override a specific Spring bean locally rather than allow global bean definition overriding?如何在本地覆盖特定的 Spring bean 而不是允许全局 bean 定义覆盖?
【发布时间】:2020-07-08 03:36:17
【问题描述】:

我有一个第三方 @Configuration 类,它定义了一个我想用我自己的版本替换的 bean,但我不想排除该配置,因为它定义了我需要的许多其他 bean。相反,我想实现这样的目标:

@Configuration
class ThirdPartyConfig {

    ...

    // unfortunately, there's no @ConditionalOnMissingBean annotation here
    @Bean
    internal fun someBean() = ...

}

@Configuration
@Import(ThirdPartyConfig::class)
class MyLocalConfig {

    // overrides "someBean" in `ThirdPartyConfig`
    @Bean(overrideExistingBeanWithSameNameIfAny = true)
    fun someBean() = ...

}

在 Spring / Spring Boot 中可以吗?

【问题讨论】:

  • 为什么不只包含 bean 副本的配置,然后根据本地配置对其进行修改?
  • 因为它是按名称注入到ThirdPartyConfig 中定义的其他bean。我不能告诉他们使用不同的 bean。
  • 你试过了吗?

标签: java spring spring-boot kotlin


【解决方案1】:

您可以为您的自定义 bean 使用 @Primary 注释。

@Configuration
@Import(ThirdPartyConfig::class)
class MyLocalConfig {

    @Primary
    @Bean
    fun someBean() = ...

}

【讨论】:

  • 那行不通。 @Primary 不会以任何方式影响 bean 覆盖。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-18
  • 2018-10-18
  • 1970-01-01
相关资源
最近更新 更多