前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ApplicationContextAware

ApplicationContextAware

作者头像
allsmallpig
发布2023-10-19 18:24:47
1270
发布2023-10-19 18:24:47
举报
文章被收录于专栏:allsmallpi博客allsmallpi博客
代码语言:javascript
复制
package com.***.springboot;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import com.*.commons.util.SnowflakeIdWorker;
import com.*.springboot.jwt.model.JwtUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 上下文中间件
 * @author:  
 * @created: 2020-01-23 13:38
 * ---------------------------------------------------
 * 日期          时间    修改人       修改说明
 * 2020-01-23   13:38   初始化文件
 * ---------------------------------------------------
 **/
@Component
public class ApplicationFactory implements ApplicationContextAware {


    private static ApplicationContext context;

    /**
     * 应用流水号;负载的时候,用于识别当前的应用号
     * 在启动jvm的参数中加上: -Dapp.serial.no=ssm1
     */
    public static String appSerialNo="";

    public static Set<String> profiles;


    public static Set<String> beanNameSet;

    private static SnowflakeIdWorker idWorker = new SnowflakeIdWorker();

    public static GenericFastJsonRedisSerializer serializer = new GenericFastJsonRedisSerializer();

    public static long nextId(){
        return idWorker.nextId();
    }

    /**
     * 自定义的mybatis表
     */
    public static Map<String,String> myBatisPlusTableMap = new HashMap<>(1000);
    public static String[] preloadPkgs;


//    public static Map<String, BufferedImage> imageMap = new ConcurrentHashMap<>(100);

    public static JwtUser innerJwtUser;

    // 创建 SecureRandom 对象,并设置加密算法
    private static SecureRandom secureRandom;
    private static ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();

    static {
        try {
            secureRandom = SecureRandom.getInstance("SHA1PRNG");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    public static String randomNext(int max){
        if(secureRandom==null){
            return String.valueOf(threadLocalRandom.nextInt(max));
        }
        return String.valueOf(secureRandom.nextInt(max));
    }

    /**
     * 获取服务
     * @param beanName bean名称
     * @param <T> 返回的类型
     * @return 泛型
     */
    public static <T> T getBean(String beanName){

        if(beanNameSet==null){
            return null;
        }

        if(beanNameSet.contains(beanName)){
            return (T)getApplicationContext().getBean(beanName);
        }

        return null;
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
        List<String> names = Arrays.asList(applicationContext.getBeanDefinitionNames());
        //System.out.println(names.stream().filter(a->a.contains("facadeService_")).collect(Collectors.joining(",")));
        beanNameSet = new HashSet<>(names);
    }

    public static ApplicationContext getApplicationContext() {
        return context;
    }



    private static String[] getNullPropertyNames (Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<>();
        for(java.beans.PropertyDescriptor pd : pds) {
            Method readMethod = pd.getReadMethod();
            if(readMethod==null){
                emptyNames.add(pd.getName());
                continue;
            }
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    public static void copyPropertiesIgnoreNull(Object src, Object target){
        BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
    }

    private static boolean logQmPush = false;
    private static boolean logYjyc = false;
    private static boolean logXijieYc = false;
    private static boolean logKdPush = false;
    private static boolean logFqReq = true;
    private static boolean apixd = true;
    private static boolean logMqConsume = false;

    public static void setLogFlag(String m,boolean v){
        switch (m.toUpperCase()){
            case "QM":
                logQmPush = v;
                break;
            case "YJYC":
                logYjyc = v;
                break;
            case "XIJIE":
                logXijieYc = v;
                break;
            case "KD":
                logKdPush = v;
                break;
            case "FQ":
                logFqReq = v;
                break;
            case "APIXD":
                apixd = v;
                break;
            case "MQ":
                logMqConsume = v;
                break;
            default:
                break;
        }
    }

    public static boolean getLogFlag(String m){
        switch (m.toUpperCase()){
            case "QM":
                return logQmPush ;
            case "YJYC":
                return logYjyc;
            case "XIJIE":
                return logXijieYc;
            case "KD":
                return logKdPush;
            case "FQ":
                return logFqReq;
            case "APIXD":
                return apixd;
            case "MQ":
                return logMqConsume;
            default:
                return false;
        }
    }

    public static String getUserRoleSn(JwtUser jwtUser){
        if(jwtUser.getAdminFlag()==1){return "";}
        return getUserRoleSn(jwtUser.getCoNo(),jwtUser.getRoles());
    }

    /**
     * 获取角色的唯一字符串(排序后:不排序的话,可能不是相等的,如:  1,3,2 和 1,2,3 )
     * ---------------------------------------------------
     * 日期          时间    修改人       修改说明
     * 2021-12-23   10:16   wagzh      分销商,店铺,仓库等共享角色下的SN返回处理
     * ---------------------------------------------------
     * @param coNo   公司编号
     * @param roles  角色集合
     * @return 字符串
     */
    public static String getUserRoleSn(Long coNo, String roles){
        if(roles.indexOf("-")>=0){
            return "0_"+Math.abs(Integer.parseInt(roles));
        }
        String userRole = roles;
        if(StringUtils.isEmpty(userRole)){
            throw new RuntimeException("用户无角色");
        }
        userRole = userRole.replace(" ","");
        List<String> roleList = new ArrayList<>();

        if(userRole.contains(",")){
            roleList.addAll(Arrays.asList(userRole.split(",")));
        }else{
            roleList.add(userRole);
        }
        roleList.sort(String::compareTo);

        return coNo+"_"+StringUtils.join(roleList,"_");
    }

    /**
     * 通知事件
     * ---------------------------------------------------
     * 日期          时间    修改人       修改说明
     * 2022-01-20   16:49   解决执行2次的问题
     * ---------------------------------------------------
     * @param event 事件
     */
    public static <T extends ApplicationEvent> void publishEvent(T event) {
        //获取父容器发送事件
        context.publishEvent(event);
    }

}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-10-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
消息队列 TDMQ
消息队列 TDMQ (Tencent Distributed Message Queue)是腾讯基于 Apache Pulsar 自研的一个云原生消息中间件系列,其中包含兼容Pulsar、RabbitMQ、RocketMQ 等协议的消息队列子产品,得益于其底层计算与存储分离的架构,TDMQ 具备良好的弹性伸缩以及故障恢复能力。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档