1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > JAVA 配置文件 路径_Java配置文件读取和路径设置

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

时间:2019-10-19 11:28:42

相关推荐

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" />

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。