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加载顺序的方式的文章就介绍到这了,更多相关spring boot bean加载顺序内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!