美文网首页
springboot 中动态注入bean

springboot 中动态注入bean

作者: 我想放假休息 | 来源:发表于2021-01-27 20:46 被阅读0次

DynamicBeanHanderService


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author HQLD
 * @description
 * @date 2021-01-27 20:13
 */
@Service
public class DynamicBeanHanderService {
    @Autowired
    ApplicationContext applicationContext;
    /**
     * 通过BeanDefinition注册bean到spring context,无则加入,有则修改
     *
     * @param beanId
     * @param classPath 类路径
     * @param pvs       bean属性值
     */
    public void register(String beanId, String classPath, Map<String, Object> pvs) {
        BeanDefinition bdef = new GenericBeanDefinition();
        bdef.setBeanClassName(classPath);
        if (pvs != null && pvs.size() > 0) {
            for (String p : pvs.keySet()) {
                bdef.getPropertyValues().add(p, pvs.get(p));
            }
        }
        DefaultListableBeanFactory fty = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
        fty.registerBeanDefinition(beanId, bdef);
    }

    /**
     * 动态注销bean
     *
     * @param beanId
     */
    public void destory(String beanId) {
        DefaultListableBeanFactory fty = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
        if (fty.containsBean(beanId)) {
            fty.removeBeanDefinition(beanId);
        }
    }

    /**
     * 获取bean
     *
     * @param beanId
     */
    public Object getBean(String beanId) {
        try {
            return applicationContext.getBean(beanId);
        } catch (Exception e) {
            //e.printStackTrace() ;
            return null;
        }
    }
    public <T> T getBean(String beanId, Class<T> tClass) {
        try {
            Object bean = this.getBean(beanId);
            if (bean !=null && bean.getClass() == tClass) {
                return (T) bean;
            }
            return null;
        } catch (Exception e) {
            //e.printStackTrace() ;
            return null;
        }
    }

    /*
     * 示例:
     *         String classPath = "org.hqld.wx.service.One";
     *         Map<String, Object> pvs = new HashMap<>();
     *         pvs.put("one","123");
     *         beanHanderService.register("one",classPath,pvs);
     *         One one = beanHanderService.getBean("one", One.class);
     *         System.out.println(one);
     */
}

相关文章

网友评论

      本文标题:springboot 中动态注入bean

      本文链接:https://www.haomeiwen.com/subject/gcqzzktx.html