首页  >  文章  >  Java  >  spring或spring boot怎么调整bean加载顺序

spring或spring boot怎么调整bean加载顺序

WBOY
WBOY转载
2023-05-11 12:10:132406浏览

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 返回数值, 数值越小说明优先级越高。

以上是spring或spring boot怎么调整bean加载顺序的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:yisu.com。如有侵权,请联系admin@php.cn删除