canna-cloud【四】spring boot的bean延迟初始化
程序员文章站
2022-05-21 19:17:42
...
逻辑:
1、定义初始化抽象接口InitService
2、通过监听器,在启动完成后,遍历所有的bean,判断是否实现了接口InitService。
3、如果实现了接口,则调用接口中的初始化方法,并根据接口定义的初始化顺序先后进行初始化。
public interface InitService {
/*
* order 越大 约先初始化
*/
/**
* 拦截器
*/
static final Integer INTERCEPT_ORDER = 1000; // >= 1000
/**
* 队列
*/
static final Integer QUEUE_ORDER = 2000; // >= 2000
/**
* 控制器
*/
static final Integer CONTROLLER_ORDER = 3000; // >= 3000
/**
* 定时任务
*/
static final Integer SCHEDULE_ORDER = 4000; // >= 4000
/**
* service服务
*/
static final Integer SERVICE_ORDER = 5000; // >= 5000
/**
* 配置实例化
*/
static final Integer CONFIGURE_ORDER = 6000; // >= 6000
int getOrder();
void init() throws CannaException;
}
public class EndStartedListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (((ApplicationContextEvent) event).getApplicationContext().getParent() == null) {
try {
this.initSystem(SpringContextHolder.getApplicationContext());
} catch (CannaException e) {
log.error("", e);
}
}
}
public void initSystem(ApplicationContext context) throws CannaException {
String beans[] = context.getBeanDefinitionNames();
log.info("bean length:{}", beans.length);
Map<Integer, List<Object>> beanMap = new HashMap<Integer, List<Object>>();
for (String bean : beans) {
Object obj = context.getBean(bean);
if (obj instanceof InitService) {
InitService initService = (InitService) obj;
Integer key = initService.getOrder();
List<Object> beanList = beanMap.get(key);
if (beanList == null) {
beanList = new ArrayList<Object>();
beanMap.put(key, beanList);
}
beanList.add(initService);
}
}
if (beanMap.isEmpty()) {
return;
}
Set<Integer> keySet = beanMap.keySet();
Integer[] keyArr = keySet.toArray(new Integer[]{});
Arrays.sort(keyArr);
for (int i = keyArr.length - 1; i >= 0; i--) {
Integer IKey = keyArr[i];
List<Object> beanList = beanMap.get(IKey);
for (Object obj : beanList) {
if (obj instanceof InitService) {
InitService initService = (InitService) obj;
initService.init();
}
}
}
}
}