spring常用方法

1. 读取配置文件信息

方式一:

java 复制代码
// 获取文件路径
String fileName = "application.yaml";
String filePath = this.getClass().getClassLoader().getResource(fileName).getPath();

BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
Stringline = null;
StringBuilder fileData = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
    fileData.append(line).append(System.lineSeparator());
}
bufferedReader.close();

//或
StringBuilder fileData = new StringBuilder();
int value;
while ((value = bufferedReader.read()) != -1) {
    char c = (char) value;
    fileData.append(c);
}
bufferedReader.close();

//或使用hutool的IoUtil
String fileData = IoUtil.read(new FileInputStream(path), Charset.forName("UTF-8"));
System.out.println(fileData);

方式二:

java 复制代码
String fileName = "application.yaml";
ClassPathResource classPathResource = new ClassPathResource(fileName);
String fileData = IoUtil.read(classPathResource.getStream(), Charset.forName("utf-8"));

方式三:

java 复制代码
String fileData = IoUtil.read(JDBCUtils.class.getClassLoader().getResourceAsStream("application.yaml"), Charset.forName("UTF-8"));
System.out.println(fileData);

方式四:

java 复制代码
String fileData = IoUtil.read(ResourceUtil.getStream("application.yaml"), Charset.forName("UTF-8"));
System.out.println(fileData);
相关推荐
Exclusive_Cat27 分钟前
SpringMVC参数接收与数据返回详解
spring·mvc
ChinaRainbowSea2 小时前
补充:问题:CORS ,前后端访问跨域问题
java·spring boot·后端·spring
hqxstudying4 小时前
java依赖注入方法
java·spring·log4j·ioc·依赖
春生野草4 小时前
关于SpringMVC的整理
spring
Bug退退退1235 小时前
RabbitMQ 高级特性之重试机制
java·分布式·spring·rabbitmq
hello早上好6 小时前
CGLIB代理核心原理
java·spring
先睡12 小时前
Redis的缓存击穿和缓存雪崩
redis·spring·缓存
Bug退退退12317 小时前
RabbitMQ 高级特性之死信队列
java·分布式·spring·rabbitmq
booooooty1 天前
基于Spring AI Alibaba的多智能体RAG应用
java·人工智能·spring·多智能体·rag·spring ai·ai alibaba
极光雨雨1 天前
Spring Bean 控制销毁顺序的方法总结
java·spring