Home > Software engineering >  Multiple @ConditionalOnMissingBean bean which will be used
Multiple @ConditionalOnMissingBean bean which will be used

Time:09-16

I have multiple bean be annotated with @ConditionalOnMissingBean, which will be used? How can i control the priority?

CodePudding user response:

If you want to control @Bean creation ordering, you can use the annotation @Order

@Component
@Order(1)
public class First {

    public int first() {
        return 1;
    }
}

@Component
@Order(2)
public class Second {

    public int second() {
        return 2;
    }
}

Or you can also use @DependsOn

@Configuration
public class ActionCfg {
 
    @Bean
    @DependsOn({"actionA","actionB"})
    public ActionC actionC(){
        return new ActionC();
    }
    
    @Bean("ActionA")
    public ActionA actionA() {
        return new ActionA();
    }
    
    @Bean("ActionB")
    public ActionB actionB() {
        return new ActionB();
    }   
}

ActionA and ActionB will initialized before ActionC.

CodePudding user response:

The bean whose auto-configuration class is run first will be taken.

There is @AutoConfigureBefore, @AutoConfigureAfter and @AutoConfigureOrder to control the order of auto-configuration classes.

  • Related