接下來講解三種調整類別載入順序的方式:
@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中文網其他相關文章!