亲宝软件园·资讯

展开

spring 或者spring boot 调整bean加载顺序的方式

zhongzunfa 人气:0

spring 或者spring boot 调整bean 的加载顺序

接下来讲解三种调整类加载顺序的方式:

1、使用@Order调整配置类加载顺序

@Configuration
@Order(1)
public class ConfigA {
    @Bean
    public ServiceA serviceA(){
        System.out.println("ConfigA 执行");
        return new ServiceA();
    }
}
@Configuration
@Order(2)
public class ConfigB {
    @Bean
    public ServiceB serviceB(){
        System.out.println("ConfigB 执行");
        return new ServiceB();
    }
}

2、使用@Order调整配置类加载顺序

@Configuration
public class Config {
    @Bean
    @Order(1)
    public CListener bListener(){
        return new CListener();
    }

     @Bean
     @Order(2)
    public DListener dListener(){
        return new DListener();
    }
}

3、实现ordered 接口:

public class AListener implements ApplicationListener<ContextRefreshedEvent>, Ordered {

    private CuratorManagerComponent curatorManagerComponent;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

        logger.info("AListener 执行了。");

    }

    @Override
    public int getOrder() {

        return HIGHEST_PRECEDENCE;
    }
}
public class BListener implements ApplicationListener<ContextRefreshedEvent>, Ordered {

    private CuratorManagerComponent curatorManagerComponent;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

        logger.info("BListener 执行了。");

    }

    @Override
    public int getOrder() {

        return HIGHEST_PRECEDENCE + 2;
    }
}

@Configuration
public class Config {

    @Bean
    public BListener bListener(){
        return new BListener();
    }

     @Bean
    public AListener aListener(){
        return new AListener();
    }
}

对于实现ordered方式, 的需要在 getOrder 返回数值, 数值越小说明优先级越高。

加载全部内容

相关教程
猜你喜欢
用户评论