Ai
2 Star 3 Fork 1

汪少棠/java-se

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
ResourceBundleController.java 2.41 KB
一键复制 编辑 原始数据 按行查看 历史
package org.example.controller;
import cn.hutool.core.util.StrUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.*;
/**
* ResourceBundle 读取 *.properties 资源文件内容.
* 即便是打包成 .jar、.war 包部署到生产环境,照样读取正常。
*
* @author wangMaoXiong
* @version 1.0
* @date 2021/4/2 19:20
*/
@RestController
public class ResourceBundleController {
/**
* ResourceBundle 主要用于读取类路径下的 *.properties 资源文件,实现语言国际化
* http://localhost:8080/resourceBundle/findAllByClassPath
*
* @param classPath
* @return
*/
@GetMapping("resourceBundle/findAllByClassPath")
public Map<String, String> findAllByClassPath(String classPath) {
Map<String, String> stringMap = new HashMap<>();
classPath = StrUtil.isBlank(classPath) ? "config/config2" : classPath;
// 如果资源文件不是在类路径根目录下,则使用 "/" 或者 "." 符号,如 data/config、data.config 都可以,但是不要再写后缀名 '.properties'
// 如果类路径下找不到指定的属性文件,则抛出异常 MissingResourceException: Can't find bundle for base name xxx
ResourceBundle resourceBundle = ResourceBundle.getBundle(classPath);
// value 可以不存在,但是如果 key 为 null 或者不存在,则抛出异常。可以使用 containsKey(String key) 先判断是否 key 存在
String name = resourceBundle.getString("name");
String password = resourceBundle.getString("password");
String color = resourceBundle.getString("color");
String[] colors = resourceBundle.getString("color").split(",");
Enumeration<String> enumeration = resourceBundle.getKeys();
System.out.println("name=" + name + ", password" + password + ", color=" + color);
System.out.println(Arrays.asList(colors));
System.out.println("===============");
while (enumeration.hasMoreElements()) {
String elementName = enumeration.nextElement();
String elementValue = resourceBundle.getString(elementName);
System.out.println(elementName + "=" + elementValue);
stringMap.put(elementName, elementValue);
}
// {"password":"123456","color":"red,yellow,blue","name":"root"}
return stringMap;
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/wangmx1993/java-se.git
git@gitee.com:wangmx1993/java-se.git
wangmx1993
java-se
java-se
master

搜索帮助