接下来讲解三种调整类加载顺序的方式:
@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(); } }
@Configuration public class Config { @Bean @Order(1) public CListener bListener(){ return new CListener(); } @Bean @Order(2) public DListener dListener(){ return new DListener(); } }
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中文网其他相关文章!