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;
	}
}
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值