利用反射加载yml文件与加载缓存给实体类赋值

1.利用反射读取到项目中的yml文件

// ConfigureProperties为实体类
public static ConfigureProperties loadLocalConfig(){
        InputStream is = null;
     
            ConfigureProperties configureConfigProperties = (ConfigureProperties)ConfigureUtil.loadLocalYmlConfig("configure.yml",ConfigureProperties.class);
         
            return configureConfigProperties;
        }catch (Exception ex){
            logger.info("加载配置失败",ex);
        }finally {
            if(is!=null){
                try{
                    is.close();
                }catch (Exception ex){}
            }
        }
        return null;
    }
//根据目录加载出配置文件信息
public static Object loadLocalYmlConfig(String fileName,Class theRoot){
        if(StringUtils.isBlank(fileName) || theRoot==null){
            return null;
        }
        InputStream is = null;
        try{
            Constructor constructor = new Constructor(theRoot);
            Yaml yaml = new Yaml(constructor);
            is = ConfigureUtil.class.getResourceAsStream("/"+fileName);
            return yaml.load(is);
        }catch (Exception ex){
            logger.error("加载yml配置失败",ex);
        }finally {
            if(is!=null){
                try{
                    is.close();
                }catch (Exception ex){}
            }
        }
        return null;
    }

2.反射技术加载出redis中信息,给实体类赋值。

public static Map<ConfigureType,ConfigProperties> initCachePublicConfigProperties(Map<String, String> cacheConfig){
        if(cacheConfig==null){
            return null;
        }
        logger.info("【统一配置读取】开始读取缓存公共配置");
        //实体类所在路径
        String packageName="com.***.***.***.***.properties";
        // 扫包
        Reflections reflections = new Reflections(packageName);
        // 反射出子类
        //ConfigProperties是一个抽象类,其它的实体类都继承该类
        Set<Class<? extends ConfigProperties>> set = reflections.getSubTypesOf( ConfigProperties.class ) ;
        Map<ConfigureType,ConfigProperties> configPropertiesMap_temp=new HashMap<>();
        set.forEach(a->{
            try{
                ConfigureTypeAnnotate configureTypeAnnotate=(ConfigureTypeAnnotate) a.getAnnotation(ConfigureTypeAnnotate.class);
                if(configureTypeAnnotate!=null){
                    configPropertiesMap_temp.put(configureTypeAnnotate.config(),((ConfigProperties)a.newInstance()));
                }
            }catch (Exception ex){
                logger.error("【统一配置读取】反射获取"+a.getName()+"对象失败",ex);
            }
        });
        if(configPropertiesMap_temp.size()==0){
            logger.error("【统一配置读取】失败,无法反射获取初始化配置类信息");
            return null;
        }
        configPropertiesMap_temp.forEach((key,value)->{
            Field[] declaredFields = value.getClass().getDeclaredFields();
            for(Field field:declaredFields){
                try{
                    if(field.getType().getSuperclass().getName().equals(ConfigProperties.class.getName())){
                        field.setAccessible(true);
                        ConfigProperties subObject=(ConfigProperties)field.getType().newInstance();
                        Field[] subFields = field.getType().getDeclaredFields();
                        for(Field subField : subFields){
                            String subFieldValue=cacheConfig.get(key.getPrefix()+"."+field.getName()+"."+subField.getName());
                            setFieldValue(subObject,subField,subFieldValue);
                        }
                        field.set(value,subObject);
                    }else{
                        String fieldValue=cacheConfig.get(key.getPrefix()+"."+field.getName());
                        setFieldValue(value,field,fieldValue);
                    }
                }catch (Exception ex){
                    logger.error("【统一配置读取】反射设置"+value.getClass().getName()+"的属性"+field.getName()+"赋值失败",ex);
                }
            }
        });
        logger.info("【统一配置读取】读取缓存公共配置完成");
        return configPropertiesMap_temp;
    }
// 根据指端类型转换成相应的类型值
private static void setFieldValue(Object object,Field field,String fieldValue) throws Exception{
        if(fieldValue==null){
            return;
        }
        field.setAccessible(true);
        //支持基本数据类型 和 Set<String> List<String>
        if(field.getType().getName().equals("int") || field.getType().getName().equals("java.lang.Integer")){
            field.set(object,Integer.parseInt(fieldValue));
        }else if(field.getType().getName().equals("boolean") || field.getType().getName().equals("java.lang.Boolean")){
            field.set(object,Boolean.parseBoolean(fieldValue));
        }else if(field.getType().getName().equals("double") || field.getType().getName().equals("java.lang.Double")){
            field.set(object,Double.parseDouble(fieldValue));
        }else if(field.getType().getName().equals("long") || field.getType().getName().equals("java.lang.Long")){
            field.set(object,Long.parseLong(fieldValue));
        }else if(field.getType().getName().equals("short") || field.getType().getName().equals("java.lang.Short")){
            field.set(object,Short.parseShort(fieldValue));
        }else if(field.getType().getName().equals("java.util.List") || field.getType().getName().equals("java.util.ArrayList")){
            String[]temp=fieldValue.replace("[", "").replace("]", "").split(",");
            field.set(object, Arrays.asList(temp));
        }else if(field.getType().getName().equals("java.util.Set") || field.getType().getName().equals("java.util.HashSet")){
            String[]temp=fieldValue.replace("[", "").replace("]", "").split(",");
            field.set(object, new HashSet<>(Arrays.asList(temp)));
        }else{
            field.set(object,fieldValue);
        }
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回答: SpringBoot在启动加载配置文件时,默认会加载application.yml或application.properties文件,如果没有明确指定spring.profiles.active属性。\[1\]如果你的项目是一个SpringBoot项目而不是SpringCloud项目,只会识别application.yml配置文件,不会读取bootstrap.yml/properties文件。\[2\]如果想在SpringBoot项目中使用bootstrap.yml配置,需要添加依赖spring-cloud-context。\[2\]在yml文件中,key: value的冒号后面需要有一个空格。\[3\]如果想让SpringBoot加载自定义的yml配置文件,可以使用@PropertySource注解和@Value注解来指定目标属性在yml文件中的全限定名。同时,需要将目标类标记为@Component,以将其实例化到Spring容器中。\[3\] #### 引用[.reference_title] - *1* *2* [springcloud+springboot框架 动态加载配置文件 bootstrap.yml/properties文件](https://blog.csdn.net/qq_40448069/article/details/124929353)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Springboot加载自定义yml文件配置的方法](https://blog.csdn.net/u010922732/article/details/91048606)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值