JAVA编码(14)——JAVA创建缓存机制和监听器

本文介绍了一种在项目启动时加载配置文件的方法,并通过监听器实现配置信息的缓存,以便后续直接调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目的:就是在项目启动的时候就去加载配置文件的信息,后期当需要配置信息中的内容 ,就可以直接去获取.

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
  
 

 

  

转载于:https://www.cnblogs.com/xushuyi/articles/4394548.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值