看下面这两个例子,哪个bean会加载?
例1
/** * AaAutoConfiguration先加载 */ @Configuration public class AaAutoConfiguration{ @Bean @ConditionalOnMissingBean(name="testBeanName") public TestBean testBeanName(){ return new TestBean(); } } /** * BbAutoConfiguration后加载 */ @Configuration public class BbAutoConfiguration{ @Bean @ConditionalOnMissingBean(name="testBeanName") public TestBean2 testBeanName(){ return new TestBean2(); } }
答案:AaAutoConfiguration#testBeanName
例2
/** * AaAutoConfiguration先加载 */ @Configuration public class AaAutoConfiguration{ @Bean @ConditionalOnMissingBean(name="testBeanName") public TestBean testBeanName(){ return new TestBean(); } } /** * BbAutoConfiguration后加载 */ @Configuration public class BbAutoConfiguration{ @Bean @ConditionalOnMissingBean public TestBean2 testBeanName(){ return new TestBean2(); } }
答案:BbAutoConfiguration#testBeanName
为什么呢?
触发问题条件:Bean ClassType 不一样+ConditionalOnMissingBean未指定name
查看spring代码 ConfigurationClassBeanDefinitionReader#loadBeanDefinitionsForBeanMethod方法
具体代码 conditionEvaluator.shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN)
内部调用 ConditionalOnMissingBean的判断逻辑
根据注解配置 ,先判断类型 ->再判断annotaion→最后判断beanNames(判断排除ignoreTypes)
如果未匹配到,覆盖beanDefinition
版权声明:《 AutoConfiguration加载顺序问题 》为Saber原创文章,转载请注明出处!
最后编辑:2023-9-18 04:09:55