RuoYi-Vue 前后端分离版代码浅析-Common层中获得bean

300 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

前言

本节介绍RuoYi-Vueruoyi-admin模块中的字典类型模块SysDictTypeController 部分的代码,这个接口主要用来展示字典类型的情况,主要是增删改查,比较有意思的是刷新字典缓存这个方法,

从Common层中获取Spring上下文

/**
 * 刷新字典缓存
 */
@PreAuthorize("@ss.hasPermi('system:dict:remove')")
@Log(title = "字典类型", businessType = BusinessType.CLEAN)
@DeleteMapping("/refreshCache")
public AjaxResult refreshCache() {
    dictTypeService.resetDictCache();
    return AjaxResult.success();
}

对应的重置代码中使用了

/**
 * 重置字典缓存数据
 */
@Override
public void resetDictCache() {
    clearDictCache();
    loadingDictCache();
}
/**
 * 清空字典缓存数据
 */
@Override
public void clearDictCache() {
    DictUtils.clearDictCache();
}
/**
 * 加载字典缓存数据
 */
@Override
public void loadingDictCache() {
    List<SysDictType> dictTypeList = dictTypeMapper.selectDictTypeAll();
    for (SysDictType dictType : dictTypeList) {
        List<SysDictData> dictDatas = dictDataMapper.selectDictDataByType(dictType.getDictType());
        DictUtils.setDictCache(dictType.getDictType(), dictDatas);
    }
}

DictUtils.setDictCache 这个方法需要在Common层中访问RedisCache

/**
 * 清空字典缓存
 */
public static void clearDictCache()
{
    Collection<String> keys = SpringUtils.getBean(RedisCache.class).keys(Constants.SYS_DICT_KEY + "*");
    SpringUtils.getBean(RedisCache.class).deleteObject(keys);
}

所以就用到了


/**
 * spring工具类 方便在非spring管理环境中获取bean
 *
 * @author ruoyi
 */
@Component
public final class SpringUtils implements BeanFactoryPostProcessor, ApplicationContextAware {
    /**
     * Spring应用上下文环境
     */
    private static ConfigurableListableBeanFactory beanFactory;

    private static ApplicationContext applicationContext;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        SpringUtils.beanFactory = beanFactory;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }

    /**
     * 获取对象
     *
     * @param name
     * @return Object 一个以所给名字注册的bean的实例
     * @throws org.springframework.beans.BeansException
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        return (T) beanFactory.getBean(name);
    }

    /**
     * 获取类型为requiredType的对象
     *
     * @param clz
     * @return
     * @throws org.springframework.beans.BeansException
     */
    public static <T> T getBean(Class<T> clz) throws BeansException {
        T result = (T) beanFactory.getBean(clz);
        T result1 = (T) applicationContext.getBean(clz);
        return result;
    }

这里的 ConfigurableListableBeanFactory beanFactoryApplicationContext applicationContext实际上都可以用来访问当前的上下文中的bean,具体的区别可以参看www.cnblogs.com/xiaoxi/p/58… 这里面有详细的介绍,不再赘述。