web.xml中添加监听器:
<listener>
<listener-class>
com.sinosoft.mm.listener.LoadLocationPropertiesListener
</listener-class>
</listener>
监听方法:监听src下的配置信息:
package com.sinosoft.mm.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.log4j.Logger;
import sinosoftoa.presentation.workflow.LoadLocationProperties;
public class LoadLocationPropertiesListener implements ServletContextListener {
private final Logger logger = Logger.getLogger(LoadLocationPropertiesListener.class);
public void contextDestroyed(ServletContextEvent event) {
// TODO Auto-generated method stub
try {
} catch (Exception e) {
System.out.println(" 监听器销毁失败 exception:"+e.toString());
}
}
public void contextInitialized(ServletContextEvent event) {
try {
// load location.properties
LoadLocationProperties.setProperties("/location.properties");
// load log4j.properties
LoadLocationProperties.setProperties("/log4j.properties");
} catch (Exception e) {
logger.error(e.getMessage(),e);
System.out.println(" 监听器初始化 exception:"+e.toString());
}
}
}
将读取的配置信息装入到map中:
package sinosoftoa.presentation.workflow;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;
import org.apache.log4j.Logger;
public class LoadLocationProperties {
private static final Logger logger = Logger.getLogger(LoadLocationProperties.class);
//Properties cache
public static Map<String, Properties> pMap = new Hashtable<String, Properties>();
public static void setProperties(String name){
Properties p = new Properties();
InputStream in = null;
in = LoadLocationProperties.class.getClassLoader().getResourceAsStream("location.properties");
try {
p.load(in);
} catch (IOException e) {
System.out.println("加载location.properties失败:"+e.toString());
}finally{
try {
if (in!=null) {
in.close();
}
} catch (IOException e) {
System.out.println(""+e.toString());
}
}
logger.info("Load to properties cache :" + name);
pMap.put(name, p);
}
//Get properties by properties path
public static Properties getProperties(String name){
return pMap.get(name);
}
//Get properties value by properties path & key
public static String getPropertiesValue(String name,String key){
if (pMap.get(name)==null) {
return null;
}
return pMap.get(name).getProperty(key);
}
}
项目中如何读取配置信息:
String voucherFilePath = LoadLocationProperties.getPropertiesValue("/location.properties", "voucherFilePath");