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.(key));
}
} catch (IOException e) {
System.out.Message());
}
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 = Property(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("l");
isInitialize = true;
return true;
}
catch (Exception e) {
<("Initialize spring framework failed.", e);
return false;
}
}
配置⽂件格式:
<bean id="propertyConfigurer"
class="org.springframework.fig.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>jdbc.properties</value>
<value>param.properties</value>
</list>
</property>
</bean>
ibatis配置写法:
<sqlMapConfig>
<settings cacheModelsEnabled="true" enhancementEnabled="true"
lazyLoadingEnabled="true" errorTracingEnabled="true" maxRequests="1024"
maxSessions="1000" maxTransactions="16" useStatementNamespaces="true" />    <sqlMap resource="l" />
<sqlMap resource="l" />
<sqlMap resource="l" />
</sqlMapConfig>
2)按⽂件路径加载(⽐如配置⽂件位于当前⽬录中的config⽬录下)
初始化Spring代码:
public static boolean initialize() {
if (isInitialize) {
return true;
}
try {
appContenxt = new FileSystemXmlApplicationContext("file:l");            isInitialize = true;
return true;
}
catch (Exception e) {
<("Initialize spring framework failed.", e);
return false;
spring怎么读取jar文件}
}
配置⽂件格式:
<bean id="propertyConfigurer"
class="org.springframework.fig.PropertyPlaceholderConfigurer">    <property name="locations">
<list>
<value>file:config/jdbc.properties</value>
<value>file:config/param.properties</value>
</list>
</property>
</bean>
ibatis配置写法:
<sqlMapConfig>
<settings cacheModelsEnabled="true" enhancementEnabled="true"
lazyLoadingEnabled="true" errorTracingEnabled="true" maxRequests="1024"
maxSessions="1000" maxTransactions="16" useStatementNamespaces="true" />    <sqlMap url="file:config/l" />
<sqlMap url="file:config/l" />
<sqlMap url="file:config/l" />
</sqlMapConfig>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。