properties文件放在resourses文件下
name=123
age=1
address=南京
phone=123456
url=http://www.baidu.com
static Properties prop = null ;
public static void loadProperty(){
//3种方法加载resourses目录下的spring.properties文件
// InputStream is = this.getClass().getClassLoader().getResourceAsStream("spring.properties");
InputStream is1 = PropertiesUtil.class.getResourceAsStream("/spring.properties");
// InputStream is1 = PropertiesUtil.class.getClassLoader().getResourceAsStream("spring.properties");
try {
prop = new Properties();
prop.load(is1);
} catch (IOException e) {
e.printStackTrace();
}finally {
if (is1 != null) {
try {
is1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//返回配置文件中的key对应的值
public static String getProperty(String key){
if(prop == null){
loadProperty();
}
return prop.getProperty(key);
}
//返回配置文件中的key对应的值,为null则给一个自定义的默认值
public static String getProperty2(String key,String defaultValue){
if(prop == null){
loadProperty();
}
return (String) prop.getProperty(key,defaultValue);
}
this代表当前对象,不能在static方法中使用
重点:
3种方法加载resourses目录下的spring.properties文件,如:PropertiesUtil.class.getClassLoader().getResourceAsStream(“spring.properties”);
加载的是target下的属性文件
而项目 <packaging>pom</packaging>
打包的target中没有resourses下的属性文件,这样就会加载不到属性文件
解决办法:1.将pom改为jar/war 打包后在换回来
2.手动加入属性文件(xml文件不能手动加入)
后续更新不需要重启服务器的情况下动态加载配置文件中的内容。