import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import java.util.Properties;
public class YmlConfigReader {
public static Properties getYmlFileProperties(String ymlFilePath) {
Properties properties = new Properties();
try {
// 使用Spring的PathMatchingResourcePatternResolver来加载资源文件
Resource resource = new PathMatchingResourcePatternResolver().getResource(ymlFilePath);
// 使用EncodedResource包装Resource,指定编码格式
EncodedResource encodedResource = new EncodedResource(resource, "UTF-8");
// 使用YamlPropertiesFactoryBean解析YML文件内容到Properties对象
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(encodedResource.getResource());
factory.afterPropertiesSet();
properties = factory.getObject();
} catch (Exception e) {
e.printStackTrace();
}
return properties;
}
public static void main(String[] args) {
// 示例:读取名为application.yml的配置文件
Properties props = getYmlFileProperties("classpath:application.yml");
// 打印读取到的属性
props.forEach((key, value) -> System.out.println(key + ": " + value));
}
}
getResource方法可以根据路径获取资源。Resource对象,并指定编码格式(如UTF-8),以避免读取文件时出现乱码问题。Properties对象。Properties对象。getYmlFileProperties方法读取YAML文件,并打印出所有的键值对。这个示例展示了如何在Java中使用Spring框架提供的工具类来读取和解析YAML配置文件。
上一篇:java 两个集合取交集
下一篇:java 获取日期
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站