AutoConfiguration加载顺序问题

看下面这两个例子,哪个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

发表评论 / Comment

用心评论~