spring boot读取yml配置集合,反射实战!

一 . 手动从spring中获取bean对象,工具类

    

package com.meeno.wzq.util;


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


/**
 * @description: SpringBeanUtil
 * @author: Wzq
 * @create: 2019-10-08 16:24
 */
@Component
public class SpringBeanUtil implements ApplicationContextAware {


    private static ApplicationContext applicationContext;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(SpringBeanUtil.applicationContext == null) {
            SpringBeanUtil.applicationContext = applicationContext;
        }
        System.out.println("---------------------------------------------------------------------");
        System.out.println("========ApplicationContext配置成功,在普通类可以通过调用SpringUtils.getAppContext()获取applicationContext对象,applicationContext="+SpringBeanUtil.applicationContext+"========");
        System.out.println("---------------------------------------------------------------------");
    }


    //获取applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }


    //通过name获取 Bean.
    public static Object getBean(String name){
        return getApplicationContext().getBean(name);
    }


    //通过class获取Bean.
    public static <T> T getBean(Class<T> clazz){
        return getApplicationContext().getBean(clazz);
    }


    //通过name,以及Clazz返回指定的Bean
    public static <T> T getBean(String name,Class<T> clazz){
        return getApplicationContext().getBean(name, clazz);
    }
}

    

二 . 读取yml配置文件

yml:配置如下

##加密数据标识
encryption:
  encryptionMap:
    #分类
    bank:
      objectBean: encryptionEnterpriseService
      method[0]: isRepeatByName
      method[1]: addEnterprise
      method[2]: getEnterprise
      method[3]: editEnterprise
      method[4]: editEnterpriseDetail
    #试卷
    testPaper:
      objectBean: encryptionTestpaperService
      method[0]: addTestpaper
      method[1]: editTestpaper
      method[2]: getTestpaper
      method[3]: isRepeatByName
    #试题
    question:
      objectBean: encryptionQuestionService
      method[0]: addQuestion
      method[1]: updateQuestion
    #课程
    course:
      objectBean: encryptionCourseService
      method[0]: addCourse
      method[1]: updateCourse
      method[2]: getCourseById
    #课时
    p:
      objectBean: encryptionSectionService
      method[0]: addSession
      method[1]: getSectionById
    #任务
    task:
      objectBean: encryptionScheduleService
      method[0]: addSchedule
      method[1]: getScheduleById
      method[2]: updateSchedule
    #资源
    resource:
      objectBean: encryptionBankResService
      method[0]: addBankRes
      method[1]: getBankRes
    #banner
    banner:
      objectBean: encryptionBannerService
      method[0]: addBanner
      method[1]: getBanner
      method[2]: editBanner
    #员工职位
    position:
      objectBean: encryptionEmployeePositionService
      method[0]: addEmployeePosition
      method[1]: editEmployeePositionName
      method[2]: getEmployeePositionName
      method[3]: isRepeatByName
    #银行部门
    department:
      objectBean: encryptionEmployeeDepartmentService
      method[0]: addEmployeeDepartment
      method[1]: editEmployeeDepartment
      method[2]: getEmployeeDepartmentName
      method[3]: findEmployeeDepartmentIdByName

 

开启spring配置转换为bean配置,一般在启动类上加上:

@EnableConfigurationProperties

创建读取配置的类:配置类

package com.meeno.wzq.config;


import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;


import java.util.HashMap;
import java.util.Map;


/**
 * @description: 私密数据map从配置文件中读取
 * @author: Wzq
 * @create: 2019-10-08 14:39
 */
@Component
@ConfigurationProperties(prefix = "encryption")
public class EncryptionMapConfig {


    /**
     * 从配置文件中读取的encryptionMap开头的数据
     * 注意:名称必须与配置文件中保持一致
     */
    private Map<String, Map<String,Object>> encryptionMap = new HashMap<>();


    public Map<String, Map<String,Object>> getEncryptionMap() {
        return encryptionMap;
    }


    public void setEncryptionMap(Map<String, Map<String,Object>> encryptionMap) {
        this.encryptionMap = encryptionMap;
    }


}


三.使用配置加反射,实现具体功能,(这个具体功能,是我在项目中遇到的,实际开发中,很少遇到,除非二次开发项目)

循环遍历配置的Map,根据配置获取具体的方法Method,把key为方法名称,value为反射的Method保存到另一个static的Map中,以便在其他地方使用。

package com.meeno.wzq.constants;


import com.google.common.collect.Lists;
import com.meeno.wzq.util.SpringBeanUtil;


import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @description: 私密数据Constants
 * @author: Wzq
 * @create: 2019-10-08 14:57
 */
public class EncryptionConstants {


    public static Map<String, Method> encryptionConstantsMap = new HashMap<String,Method>();


    public static void convert(Map<String,Map<String,Object>> map) throws ClassNotFoundException, NoSuchMethodException {


        for (String s : map.keySet()) {
            Map<String,Object> tempMap = map.get(s);
            String objectBeanStr = tempMap.get("objectBean").toString();
            Map<String,String> params = (Map<String,String>) ((Map) tempMap.get("method"));
            List<String> methodList = Lists.newArrayList();
            if(params!=null){
                for (String param : params.keySet()) {
                    methodList.add(params.get(param));
                }
            }
            for(String methodStr : methodList){
                Object objectBean = SpringBeanUtil.getBean(objectBeanStr);
                Class clazz = objectBean.getClass();
                Method method = null;
                for(int i = 0; i < clazz.getMethods().length; i++){
                    Method tempMethod = clazz.getMethods()[i];
                    String methodName = tempMethod.getName();
                    if(methodName.equals(methodStr)){
                        method = tempMethod;
                        break;
                    }
                }
                encryptionConstantsMap.put(methodStr,method);
            }
        }
    }




}


四 . 加载类,项目启动时运行

package com.meeno.wzq.runner;


import com.meeno.trainsys.schedule.service.LearningScheduleService;
import com.meeno.wzq.config.EncryptionMapConfig;
import com.meeno.wzq.constants.EncryptionConstants;
import com.meeno.wzq.util.AuthorizationServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;


/**
 * @program: server-java
 * @description: 启动项目时启动项目
 * @author: Wzq
 * @create: 2019-06-27 20:00
 */
@Component
@Order(value = 1)
public class MyApplicationRunner implements ApplicationRunner {


    @Autowired
    LearningScheduleService learningScheduleService;


    @Autowired
    EncryptionMapConfig encryptionMapConfig;






    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        EncryptionConstants.convert(encryptionMapConfig.getEncryptionMap());


    }
}


技术支持:高岳峰,闫宇峰,施凯雷,杨珂

他的个人博客地址:http://120.78.93.197/

这是我的公众号 有最新的it咨询,和个人工作的记录:

这是我的个人微信遇到问题欢迎,提问:

最后加上高质量的淘宝店:如有质量问题随时滴滴我,童叟无欺!

    

【童装园服定制店铺】https://m.tb.cn/h.ef2J8CD?sm=6e0f74 点击链接,再选择浏览器咑閞;或復·制这段描述¥zfwjY4JVngW¥后到淘♂寳♀

   

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值