JAVA 配置文件 路径_Java配置文件读取和路径设置

记录几种读取配置文件的方法,以及配置文件的放置路径。

1、使用PropertiesLoaderUtils工具类(springframework包提供)

优点:实时加载配置文件,修改后立即生效,不必重启

配置文件至于classpath中(与class文件放在一起,如果打jar包需打到包内),代码如下:

private static void springUtil(){

Properties props = new Properties();

while(true){

try {

props=PropertiesLoaderUtils.loadAllProperties("param.properties");

for(Object key:props.keySet()){

System.out.print(key+":");

System.out.println(props.get(key));

}

} catch (IOException e) {

System.out.println(e.getMessage());

}

try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}

}

}

2、根据文件路径读取

优点:配置文件可以放在jar包外面,根据文件路径寻找配置文件

代码如下:

public static String readValue(String fileName, String key)

{

Properties props = new Properties();

String value = null;

try

{

// 配置文件位于当前目录中的config目录下

InputStream in = new BufferedInputStream(new FileInputStream("config/" + fileName));

props.load(in);

value = props.getProperty(key);

}

catch (Exception e)

{

e.printStackTrace();

}

return value;

}

3、spring加载配置文件的两种方式

1)按classpath加载(配置文件与class文件放于同一目录)

初始化Spring代码:

public static boolean initialize() {

if (isInitialize) {

return true;

}

try {

appContenxt = new FileSystemXmlApplicationContext("spring.xml");

isInitialize = true;

return true;

}

catch (Exception e) {

logger.error("Initialize spring framework failed.", e);

return false;

}

}

配置文件格式:

class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

jdbc.properties

param.properties

ibatis配置写法:

lazyLoadingEnabled="true" errorTracingEnabled="true" maxRequests="1024"

maxSessions="1000" maxTransactions="16" useStatementNamespaces="true" />

2)按文件路径加载(比如配置文件位于当前目录中的config目录下)

初始化Spring代码:

public static boolean initialize() {

if (isInitialize) {

return true;

}

try {

appContenxt = new FileSystemXmlApplicationContext("file:config/spring.xml");

isInitialize = true;

return true;

}

catch (Exception e) {

logger.error("Initialize spring framework failed.", e);

return false;

}

}

配置文件格式:

class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

file:config/jdbc.properties

file:config/param.properties

ibatis配置写法:

lazyLoadingEnabled="true" errorTracingEnabled="true" maxRequests="1024"

maxSessions="1000" maxTransactions="16" useStatementNamespaces="true" />

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值