Springboot中使用springContext将一些方式处理成静态方法 方便直接使用

Springboot中使用springContext将一些方式处理成静态方法 方便直接使用

1.认证信息

2.配置信息等

示例:UapTokenUtil.java

package com.mingx.pms.utils;

import com.mingx.pms.constant.SystemInfo;
import com.mingx.pms.entities.utils.constant.CacheConstants;
import com.mingx.pms.exception.CustomException;
import com.mingx.pms.exception.ResultEnum;
import com.mingx.pms.utils.redis.RedisCache;

import java.util.Map;

// 静态方法调用动态方法
public class UapTokenUtil {

    public static String getTokenCache() {
        try {
            String phone = SecurityUtils.getLoginUser().getUser().getPhone();
            RedisCache redisCache = SpringContext.getBean(RedisCache.class);
            Map<String, String> tokenCache = redisCache.get(CacheConstants.UAP_TOKEN_KEY + phone, Map.class);
            if (tokenCache != null) {
                return tokenCache.get(SystemInfo.PC_TOKEN_HEADER_PARAM_NAME);
            }
        } catch (Exception e) {
            throw new CustomException(ResultEnum.UN_LOGIN_ERROR, UapTokenUtil.class.toString());
        }
        return null;
    }
}

SpringContext定义
package com.mingx.pms.utils;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

// Spring 上下文工具类
@Component
public class SpringContext implements ApplicationContextAware {
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        context = applicationContext;
    }

    public static <T> T getBean(Class<T> beanClass) {
        return context.getBean(beanClass);
    }
}

 



 

posted @ 2025-08-27 16:26  官萧何  阅读(11)  评论(0)    收藏  举报