我们在开发工程中,有时候需要在Java代码中定义一些在部署生产环境时容易改变的变量,还需要我们单独放在一个外部属性文件中,方便我们将来修改。这里列出了两种比较方便的方式。

一、在Spring配置文件中使用 util:properties 标签进行暴露 properties 文件中的内容,需要注意的是需要在Spring的配置文件的头部声明以下部分。

xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd"

1. 在classpath路径下新建 config.properties 内容如下:

app.id=appId

2. 修改Spring的配置文件

<util:properties id="appConfig" location="classpath:config.properties"></util:properties>

3. 在需要调用的类中声明全局变量,加上@Value注解

@Value("#{appConfig['app.id']}")
private String appId;

二、使用Java的Properties类

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties; /**
* properties文件获取工具类
*/
public class PropertyUtil { private static Properties props;
static {
loadProps();
} synchronized static private void loadProps(){
System.out.println("开始加载properties文件内容.......");
props = new Properties();
InputStream in = null;
try {
// 第一种,通过类加载器进行获取properties文件流-->
in = PropertyUtil.class.getClassLoader().getResourceAsStream("db.properties");
// 第二种,通过类进行获取properties文件流-->
//in = PropertyUtil.class.getResourceAsStream("/jdbc.properties");
props.load(in);
} catch (FileNotFoundException e) {
System.out.println("jdbc.properties文件未找到");
} catch (IOException e) {
System.out.println("出现IOException");
} finally {
try {
if(null != in) {
in.close();
}
} catch (IOException e) {
System.out.println("jdbc.properties文件流关闭出现异常");
}
}
System.out.println("加载properties文件内容完成...........");
System.out.println("properties文件内容:" + props);
} /**
* 根据key获取配置文件中的属性
*/
public static String getProperty(String key){
if(null == props) {
loadProps();
}
return props.getProperty(key);
} /**
* 根据key获取配置文件中的属性,当为null时返回指定的默认值
*/
public static String getProperty(String key, String defaultValue) {
if(null == props) {
loadProps();
}
return props.getProperty(key, defaultValue);
}
}

测试:

String appId = PropertyUtil.getProperty("app.id");
System.out.println("appId = " + appId);

最新文章

  1. 学习Google Protocol buffer之语法
  2. 注解:【无连接表的】Hibernate单向1-&gt;N关联
  3. TYVJ P1008 传球游戏
  4. self进行weak化
  5. 获取当前匹配元素 包括自身的html
  6. (转)TeamCity配置笔记
  7. Spring 操作数据库
  8. iOS中关于KVC与KVO知识点
  9. 点分治练习: boatherds
  10. ANCS协议翻译
  11. WebMatrix安装和使用
  12. session相关----高手请跳过!
  13. SVN的目录管理规范
  14. 在ssm框架中前后台数据交互均使用json格式
  15. CSS预处理器之Less详解
  16. MySql 主从同步 (库名不同)
  17. Instruments Time Profiler时,无法定位代码,如何破?
  18. mysql 忘记密码解决方案
  19. Nodejs 使用特定版本的SSL/TLS协议版本
  20. 微信 小程序组件 加入购物车全套 one wxml

热门文章

  1. HttpHelps类
  2. 安装arcgis server完成,打开出现未关联错误怎么办
  3. 关于PC端与手机端随着手指移动图片位置放生变化的拖拽事件
  4. incredibuild agent service is not running
  5. Math 对象 识记
  6. Debian搭建PPTPD
  7. (转载)#include机制,#ifndef...#define...#endif防止重复引用,声明,定义等概念
  8. 精简CSS
  9. 浅谈MacOS-20155205郝博雅
  10. 模拟点击a链接