【问题标题】:Spring autoconfigurations, @ConditionalOnBean with a @RepositorySpring 自动配置,@ConditionalOnBean 和 @Repository
【发布时间】:2020-05-11 11:21:47
【问题描述】:

我有一个启动模块,它公开了一个标记接口以及一些存储库:

interface AwesomeRepo

...

internal interface FakeRepository: Repository<JPAStub, String>, AwesomeRepo {
    fun count(): Long
}

@Entity
class JPAStub(@Id val name: String)
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(EntityManagerFactory::class)
@AutoConfigureAfter(JpaRepositoriesAutoConfiguration::class)
@EnableJpaRepositories(basePackageClasses = [FakeRepository::class])
@EntityScan(basePackageClasses = [FakeRepository::class])
class AwesomePersistenceAutoConfiguration

在另一个模块中,我有一个自动配置,它依赖于 AwesomeRepo 来实例化 AwesomeApplicationService

@Configuration(proxyBeanMethods = false)
class AwesomeAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnBean(AwesomeRepo::class)
    fun awesomeAppService(awesomeRepo: AwesomeRepo) =
            AwesomeApplicationService(awesomeRepo)

我在根项目中导入了两个自动配置启动器。

我观察:

  • AwesomeApplicationService 无法实例化,因为找不到 AwesomeRepo bean

当通过debug=true启用调试时:

AwesomeAutoConfiguration #awesomeAppService:
      Did not match:
         - @ConditionalOnBean (types: *****.AwesomeRepo; SearchStrategy: all) did not find any beans of type *******.AwesomeRepo(OnBeanCondition)
  • 我尝试将@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) 添加到AwesomePersistenceAutoConfiguration@AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE)AwesomeAutoConfiguration。它没有改变问题
  • 当我删除 @ConditionOnBean(AwesomeRepo::class) 时,AwesomeApplicationService 已正确地使用存储库实例化,一切都很好。

为什么@ConditionOnBean(AwesomeRepo::class) 没有检测到AwesomeRepo bean?

编辑:经过更多的试验和错误,似乎是顺序导致了问题,应用接受的答案有效。如果有人需要更进一步,这里有一个代码基线来说明问题:https://github.com/Nimamoh/spring-autoconfigurations-conditionalonbean-with-a-repository(接受的答案在snic-answer 分支上)

【问题讨论】:

  • 您有有效的解决方案。你有什么问题?
  • 编辑了帖子,我想知道为什么ConditionOnBean 没有检测到AwesomeRepo bean

标签: spring spring-boot kotlin spring-repositories


【解决方案1】:

AwesomeAutoConfiguration 应该在AwesomePersistenceAutoConfiguration 之后排序,以便在条件启动之前处理存储库的 bean 定义。

@ConditionalOnBean 中有专门的注释:

该条件只能匹配到目前为止已由应用程序上下文处理的 bean 定义,因此,强烈建议仅在自动配置类上使用此条件。如果候选 bean 可能由另一个自动配置创建,请确保使用此条件的 bean 在之后运行。

您可以在AwesomeAutoConfiguration 上使用@AutoConfigureAfter(AwesomePersistenceAutoConfiguration.class) 来正确订购商品。

【讨论】:

    猜你喜欢
    • 2016-10-03
    • 2018-11-06
    • 2012-03-19
    • 2018-05-08
    • 2017-10-18
    • 2019-04-21
    • 1970-01-01
    • 2019-05-03
    • 2015-05-27
    相关资源
    最近更新 更多