往Springboot容器手动注册单例Bean

手动注册单例bean:

@Autowired

private ApplicationContextUtil applicationContextUtil;

@PostConstruct

public void init() {

    初始化需要注册的bean

    MqConfig mqConfig = new MqConfig();

    ....

    String beanName = "mqConfig";

    try{

        if (applicationContextUtil.getBean(beanName) != null) {

            applicationContextUtil.destroySingleton(beanName);

        }

    } catch(Throwable e) {

        log.warn("Bean {} not exist!", beanName);

    }

    applicationContextUtil.registerSingletonBean(beanName, mqConfig);

}


 

spring容器工具类:

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.support.DefaultListableBeanFactory;

import org.springframework.context.ApplicationContext;

import org.springframework.context.ConfigurableApplicationContext;

import org.springframework.stereotype.Component;

       

@Slf4j

@Component

public class ApplicationContextUtil {

    @Autowired

    private ApplicationContext applicationContext;

    /**

     * 动态注入单例bean实例

     *

     * @param beanName        bean名称

     * @param singletonObject 单例bean实例

     * @return 注入实例

     */

    public Object registerSingletonBean(String beanName, Object singletonObject) {

        //将applicationContext转换为ConfigurableApplicationContext

        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;

        //获取BeanFactory

        DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getAutowireCapableBeanFactory();

        //动态注册bean.

        defaultListableBeanFactory.registerSingleton(beanName, singletonObject);

        //获取动态注册的bean.

        return configurableApplicationContext.getBean(beanName);

    }

    public Object getBean(String beanName) {

        try {

            return applicationContext.getBean(beanName);

        } catch (Throwable e) {

            log.warn("getBean {} fail!", beanName, e);

            return null;

        }

    }

    public void destroySingleton(String beanName) {

        //将applicationContext转换为ConfigurableApplicationContext

        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;

        //获取BeanFactory

        DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getAutowireCapableBeanFactory();

        defaultListableBeanFactory.destroySingleton(beanName);

    }

}

       

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值