You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot自动配置中Bean注册顺序的决定因素是什么?

Why Module A's Bean Fails the Condition But Module B's Doesn't

The bean registration order you're seeing is determined by three key factors in Spring Boot's auto-configuration processing: module dependency hierarchy, implicit ordering from conditional bean requirements, and lack of explicit ordering constraints for your custom auto-configurations.

1. Module Dependency Hierarchy Drives A → B Ordering

Since module B explicitly depends on module A, Spring Boot ensures that auto-configurations from module A are processed before those from module B. This is a basic dependency-driven ordering rule to ensure beans from dependent modules are available when needed by their dependents.

2. Implicit Ordering from @ConditionalOnBean Creates Artemis → B Ordering

Your module B's bean uses @ConditionalOnBean(jakarta.jms.ConnectionFactory.class), which tells Spring Boot that this bean depends on the existence of a ConnectionFactory bean definition. Spring Boot's auto-configuration sorter recognizes this implicit dependency and reorders the processing sequence to run ArtemisAutoConfiguration (which provides the ConnectionFactory) before module B's auto-configuration. This ensures the required bean definition exists when evaluating B's condition.

3. No Implicit or Explicit Ordering Between A and Artemis

Module A's auto-configuration also uses @ConditionalOnBean(ConnectionFactory.class), but there's no implicit or explicit rule that forces ArtemisAutoConfiguration to run before it. Since module A is processed before B (from rule 1), and Artemis is only forced before B (rule 2), the final processing order becomes:
Module A Auto-Config → ArtemisAutoConfiguration → Module B Auto-Config

When module A's bean is evaluated, ArtemisAutoConfiguration hasn't run yet, so the ConnectionFactory bean definition doesn't exist—hence the condition fails. By the time module B's bean is evaluated, ArtemisAutoConfiguration has added the ConnectionFactory definition, so the condition passes.

Why @AutoConfigureAfter Fixes the Issue

Adding @AutoConfigureAfter(ArtemisAutoConfiguration.class) to module A's auto-configuration explicitly tells Spring Boot to run ArtemisAutoConfiguration before module A's config. This adjusts the order to:
ArtemisAutoConfiguration → Module A Auto-Config → Module B Auto-Config

Now, when module A's bean condition is evaluated, the ConnectionFactory definition already exists, so the condition passes.

内容的提问来源于stack exchange,提问作者SpaceTrucker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 08:27:06