首页 > 其他分享 >SpringBoot读取Yml配置文件工具类

SpringBoot读取Yml配置文件工具类

时间:2023-05-20 19:12:08浏览次数:36  
标签:return String 配置文件 public file path import Yml SpringBoot

SpringBoot读取Yml配置文件工具类

在某些特定的环境,需要在非SpringBean中读取Yml文件,可以使用以下方式读取:

需要依赖

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>24.1-jre</version>
        </dependency>
				<dependency>
            <groupId>org.yaml</groupId>
            <artifactId>snakeyaml</artifactId>
            <version>1.23</version>
        </dependency>
				<dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.3.3</version>
        </dependency>

读取方式

// 读取当前配置文件的数据库配置
Map<String, Object> yml = FileUtils.loadApplicationYaml();
Map<String, Object> spring = (Map<String, Object>) yml.get("spring");
Map<String, Object> datasource = (Map<String, Object>) spring.get("datasource");
String driverClassName = datasource.get("driverClassName").toString();
String username = datasource.get("username").toString();
String password = datasource.get("password").toString();
String url = datasource.get("url").toString();

工具类

package com.sinosoft.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.PathUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.*;
import com.google.common.collect.Lists;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.nio.file.FileVisitResult;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author [email protected]
 * @version 1.0
 * <p>文件处理类</p>
 * @date 2021/6/21 13:55
 */
public class FileUtils extends FileUtil {
    /**
     * 将String写入文件,覆盖模式
     *
     * @param file
     * @param data
     * @param encoding
     * @throws IOException
     */
    public static void writeStringToFile(final File file, final String data, final String encoding) throws IOException {
        writeString(data, file, encoding);
    }

    /**
     * 删除文件
     *
     * @param filePath
     *            文件
     * @return
     */
    public static boolean deleteFile(String filePath) {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }



    /**
     * 递归遍历目录以及子目录中的所有文件
     *
     * @param path
     * @param maxDepth
     * @param fileFilter
     * @return
     */
    public static List<File> list(String path, int maxDepth, FileFilter fileFilter) {
        final File file = file(path);
        List<File> fileList = Lists.newArrayList();
        if (false == exist(file)) {
            return fileList;
        } else if (false == isDirectory(file)) {
            if (null == fileFilter || fileFilter.accept(file)) {
                fileList.add(file);
            }
            return fileList;
        }

        if (maxDepth < 0) {
            // < 0 表示遍历到最底层
            maxDepth = Integer.MAX_VALUE;
        }

        Path start = file.toPath();
        PathUtil.walkFiles(start, maxDepth, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes attrs) throws IOException {
                final File file = path.toFile();
                if (null == fileFilter || fileFilter.accept(file)) {
                    fileList.add(file);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) {
                final File file = path.toFile();
                if (null == fileFilter || fileFilter.accept(file)) {
                    fileList.add(file);
                }
                return FileVisitResult.CONTINUE;
            }
        });
        return fileList;
    }

    /**
     * 递归遍历目录以及子目录中的所有文件并转换为数组
     *
     * @param path
     * @return
     */
    public static File[] loopFilesToArray(String path) {
        List<File> list = FileUtil.loopFiles(path);
        if (CollUtil.isEmpty(list)) {
            return null;
        }

        File[] files = ArrayUtil.toArray(list, File.class);
        return files;
    }

    /**
     * 获取Web项目的根路径
     *
     * @return
     */
    public static String getWebRootPath() {
        String classPath = ClassUtil.getClassPath();
        if (StringUtils.isBlank(classPath)) {
            return null;
        }

        File file = new File(classPath);
        if (URLUtil.isJarURL(ClassUtil.getClassPathURL())) {
            file = FileUtil.getParent(file, 3);
        } else {
            file = FileUtil.getParent(file, 2);
        }

        String filePath = file.getAbsolutePath();
        return filePath;
    }

    /**
     * 获取资源路径
     *
     * @param name
     * @return
     */
    public static String getPath(String name) {
        String path = FileUtil.normalize(getWebRootPath() + File.separator + name);
        FileUtil.mkdir(path);
        return path;
    }

    /**
     * 发布路径
     *
     * @return
     */
    public static String getProfilePath() {
        return getPath("profile");
    }

    /**
     * 头像路径
     *
     * @return
     */
    public static String getAvatarPath() {
        return getPath("profile/avatar");
    }

    /**
     * 临时路径
     *
     * @return
     */
    public static String getTempPath() {
        return getPath("profile/temp");
    }

    /**
     * 云盘路径
     *
     * @return
     */
    public static String getDiskPath() {
        return getPath("disk");
    }

    /**
     * 加载配置文件
     *
     * @return
     */
    public static Map<String, Object> loadApplicationYaml() {
        String resource = "application.yml";
        return loadApplicationYaml(resource);
    }

    /**
     * 加载配置文件
     *
     * @param resource
     * @return
     */
    public static Map<String, Object> loadApplicationYaml(String resource) {
        try {
            Yaml yaml = new Yaml();
            Map<String, Object> yamlMap = null;
            if (URLUtil.isJarURL(ClassUtil.getClassPathURL())) {
                String path = getPath("config/" + resource);
                String yamlStr = FileUtil.readString(path, CharsetUtil.UTF_8);
                yamlMap = yaml.load(yamlStr);
            } else {
                String yamlStr = ResourceUtil.readUtf8Str(resource);
                yamlMap = yaml.load(yamlStr);
            }

            // active
            Map<String, Object> springMap =
                    Convert.convert(new TypeReference<Map<String, Object>>() {}, yamlMap.get("spring"));
            if (MapUtil.isNotEmpty(springMap)) {
                Map<String, Object> profilesMap =
                        Convert.convert(new TypeReference<Map<String, Object>>() {}, springMap.get("profiles"));
                if (MapUtil.isNotEmpty(profilesMap)) {
                    String active = Objects.toString(profilesMap.get("active"), StringUtils.EMPTY);
                    String activeYaml =
                            "application" + "-" + active + "." + "yml";
                    Map<String, Object> activeMap = null;
                    if (URLUtil.isJarURL(ClassUtil.getClassPathURL())) {
                        String path = getPath("config/" + activeYaml);
                        String yamlStr = FileUtil.readString(path, CharsetUtil.UTF_8);
                        activeMap = yaml.load(yamlStr);
                    } else {
                        String yamlStr = ResourceUtil.readUtf8Str(activeYaml);
                        activeMap = yaml.load(yamlStr);
                    }

                    yamlMap.putAll(activeMap);
                }
            }
            return yamlMap;
        } catch (Exception e) {
            return null;
        }
    }
}

标签:return,String,配置文件,public,file,path,import,Yml,SpringBoot
From: https://www.cnblogs.com/zhangruifeng/p/17417646.html

相关文章

  • springboot的xml和java对象转换
    packagecom.zygh.tscmp.pojo;importcom.fasterxml.jackson.annotation.JsonFormat;importcom.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;importcom.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;importcom.faster......
  • springboot整合redis
     前言Redis是一款key-value存储结构的内存级NoSQL数据库支持多种数据存储格式支持持久化支持集群Redis下载(Windows版)https://github.com/tporadowski/redis/releasesRedis安装与启动(Windows版)Windows解压安装或一键式安装服务端启动命令redis-server.exe......
  • Jenkins 自动部署 SpringBoot
    Jenkins是流行的CI/DI工具。什么是CI/DI呢?CI/CD的核心概念可以总结为三点:持续集成持续交付持续部署简单来说就是将不同代码的分支合并到主分支,并自动进行打包,编译,测试,部署到生产环境的交付流程。 在这里用阿里云主机演示Jenkins自动部署SpringBoot项目。可以到阿里云官......
  • 什么是springboot&什么是spring
    1.什么是springbootspringboot是一个基于spring的开发框架,旨在简化sping应用的初始配置和开发过程。Springboot集成了对大部分目前流行的开发框架,使得开发者能够快速搭建spring项目。Springboot的核心设计思想是“约定优于配置”,基于这一原则,springboot极大地简化了项目和框架地......
  • springboot基于vue的MOBA类游戏攻略分享平台、游戏资讯分享平台,附源码+数据库+lw文档+
    1、项目介绍任何系统都要遵循系统设计的基本流程,本系统也不例外,同样需要经过市场调研,需求分析,概要设计,详细设计,编码,测试这些步骤,基于java语言设计并实现了MOBA类游戏攻略分享平台。该系统基于B/S即所谓浏览器/服务器模式,应用java技术,选择MySQL作为后台数据库。系统主要包括系统首......
  • APP-PER-5002: Oracle 人力资源管理系统无法检索用户类型配置文件选项的值。
    打开设置“职位层次结构"窗体时提示错误:APP-PER-5002:Oracle 人力资源管理系统无法检索用户类型配置文件选项的值。请确保为您的责任正确设置此值。解决方式:为该职责(例如职责全称:PO_超级管理员(CUX)) 设置配置文件(路径:SYSTEMADMINISTRATOR>> 配置文件>>系统。)。 ......
  • nginx 默认配置文件
    #usernobody;worker_processes1;#error_loglogs/error.log;#error_loglogs/error.lognotice;#error_loglogs/error.loginfo;#pidlogs/nginx.pid;events{worker_connections1024;}http{includemime.types;defau......
  • springboot异常处理
    在SpringBoot中,我们可以使用@ControllerAdvice和@ExceptionHandler来处理系统错误异常。下面是一个简单的例子:@ControllerAdvicepublicclassGlobalExceptionHandler{@ExceptionHandler(Exception.class)publicResponseEntity<String>handleException(Exceptione......
  • java基于springboot+vue的漫画网站管理系统,附源码+数据库+lw文档+PPT,适合毕业设计、课
    1、项目介绍考虑到实际生活中在漫画网站方面的需要以及对该系统认真的分析,将系统权限按管理员和用户这两类涉及用户划分。(a)管理员;管理员使用本系统涉到的功能主要有:首页、个人中心、用户管理、漫画分类管理、漫画投稿管理、分类管理、排行榜管理、交流论坛、系统管理等功能......
  • SpringBoot处理日志
    SpringBoot处理日志工作需求需要把不同类的日志分开存储,方便查阅。例如Controller的日志存一个文件,Service的日志存一个文件。需求分析日志一般都用slf4j,意思为简单日志门面,它是把不同的日志系统的实现进行了具体的抽象化,只提供了统一的日志使用接口,使用时只需要按照其提供的......