SpringIOC容器加载完Bean之后的操作
前言
有时候我们需要在Spring加载和初始化所有bean后,接着执行一些任务或者启动需要的异步服
一、ApplicationListener
在finishRefresh的publishEvent(new ContextRefreshedEvent(this));
Spring整合Nacos就是用的此种方式
@Component
public class ContextRefreshedEventListener{ //implements ApplicationListener<ContextRefreshedEvent> {
//@Async
@EventListener(ContextRefreshedEvent.class)
public void onApplicationEvent(ContextRefreshedEvent event) {
if(event.getApplicationContext().getParent() == null)//root application context 没有parent,他就是老大.
{
System.out.println("______________\n容器加载完毕\n———————");
}
}
}
二、SmartLifecycle
Spring整合Eureka就是用的此种方式
在最后一步finishRefresh的getLifecycleProcessor().onRefresh();
代码:
@Component
public class MyLifecycle implements SmartLifecycle {
private boolean started = false;
public boolean isRunning() {
return started;
}
/**
* 主要在该方法中启动任务或者其他异步服务,
* 比如开启MQ接收消息当上下文被刷新(所有对象已被实例化和初始化之后)时
*/
public void start() {
System.err.println("MyLifecycle starting");
started = true;
}
public void stop() {
System.err.println("MyLifecycle stopping");
started = false;
}
@Override
public boolean isAutoStartup() {
return true;
}
@Override
public void stop(Runnable callback) {
System.out.println("stop callback");
}
@Override
public int getPhase() {
return 0;
}
}
三、SmartInitializingSingleton
在getBean完成之后
Spring整合Ribbon用的就是此种方式
@Component
public class MySmartInitializingSingleton implements SmartInitializingSingleton {
@Override
public void afterSingletonsInstantiated() {
System.out.println("my"+"afterSingletonsInstantiated");
}
}
四、BeanPostProcessor
Spring整合Sentinel就是用的此种方式。
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if(beanName.equals("springBean")){
System.out.println("postProcessBeforeInitialization");
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if(beanName.equals("springBean")){
System.out.println("postProcessAfterInitialization");
}
return bean;
}
}