java中Properties类及读取properties中属性值
2023-04-18 14:11:42 时间
本文为博主原创,未经允许不得转载:
在项目的应用中,经常将一些配置放入properties文件中,在代码应用中读取properties文件,就需要专门的类Properties类,通过这个类可以进行读取。
深入理解和学习的参考的详见:深入理解和学习Properties参考
此处展现在项目中读取properties配置文件中的帮助类,代码可以直接使用:
*******注:读取properties文件中的属性也可以用spring boot中的注解来读取,可参考我的标签中spring boot中如何快速获取properties中的配置属性值
import java.io.IOException; import java.util.Properties; public class PropertiesUtil { public static final String FILE_PATH = "properties/upload.properties"; //通过传入的路径及key,获得对应的值 public static String getValue(String path, String key) { Properties properties = new Properties(); try { properties.load(PropertiesUtil.class.getClassLoader().getResourceAsStream(path)); } catch (IOException e) { throw new RuntimeException("File Read Failed...", e); } return properties.getProperty(key); } //通过key直接获取对应的值 public static String getValue(String key) { Properties properties = new Properties(); try { properties.load(PropertiesUtil.class.getClassLoader().getResourceAsStream(FILE_PATH)); } catch (IOException e) { throw new RuntimeException("File Read Failed...", e); } return properties.getProperty(key); } }
另外还需要在spring配置文件中,对属性文件在项目启动的时候进行初始化加载和解析:代码如下:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <bean id="configHelper" class="com.allcam.system.utils.ConfigHelper" init-method="init"> <!--进行初始化加载--> </bean> </beans>
相关文章
- Android Pie SDK与Kotlin更合拍
- 当世界上只剩下一个Java程序员
- 我来告诉你,一个草根程序员如何进入BAT
- 少走弯路,给Java 1~5 年程序员的建议
- 使用Kotlin高效地开发Android App(一)
- 2018年在Java、Web和移动开发方面值得关注的12大开源框架
- 用Java调用Oracle存储过程的示例代码解析
- Java连接DB2数据库开发应用程序的编程步骤
- 一个将SQL语句嵌入到Java应用程序中的实例
- 缓存穿透、缓存并发、热点缓存之最佳招式
- 介绍几种大型的Oracle/SQL Server数据库免费版
- Java和Ibatis调用存储过程并取得返回值详解
- Java开源NoSQL数据库大全
- 2017年9月编程语言排行榜:Java、C与C++三巨头还能统治排行榜多久?
- Java开发操作系统内核:实现进程的优先级切换
- 谈谈Java调用SQL Server分页存储过程
- 挨踢部落故事汇(23):一路前行,兴趣所至
- 如何用Java操作MongoDB
- 挨踢部落故事汇(13):扬长避短入行Oracle开发
- 高并发挑战带来的思考 看阿里如何带业务方玩转交易平台