SpringBoot读取Yml配置文件工具类
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 rayfoo@qq.com
* @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;
}
}
}