目的:就是在项目启动的时候就去加载配置文件的信息,后期当需要配置信息中的内容 ,就可以直接去获取.
public class LoadLocationProperties {
private static final Logger logger = Logger.getLogger(LoadLocationProperties.class);
//Properties cache
public static Map pMap = new Hashtable();
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);
}
}
然后创建一个监听器:
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());
}
}
}
最后在web.xml中配置一下:
com.sinosoft.mm.listener.LoadLocationPropertiesListener