Javaweb项目不用重启加载properties文件的方法(根据时间戳来判断)

来源:互联网 发布:php二次开发难吗 编辑:程序博客网 时间:2024/06/17 17:26

不多说 先来源码

package com.lx.core.util;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;


import org.apache.log4j.Logger;


public class PropertiesUtil {


private static Properties prop;


private static Logger log = Logger.getLogger(PropertiesUtil.class);

private static Long lastModified = 0l;  


private static void init() {


prop = new Properties();
String filepath = PropertiesUtil.class.getClassLoader().getResource("/properties/config.properties").getPath();
log.info(filepath);
FileInputStream fis = null;
try {
fis = new FileInputStream(filepath);
prop.load(fis);
} catch (IOException e) {
log.error("载入系统路径资源文件错误!");
e.printStackTrace();
}
}


public static String getProperty(String key) {


if (prop == null || isPropertiesModified()) {
init();
}
String value = prop.get(key).toString();
return value;
}

//判断是否被修改过  
public static boolean isPropertiesModified() {  
        boolean returnValue = false;  
        File file = new File(PropertiesUtil.class.getClassLoader().getResource("/properties/config.properties").getPath());  
        if (file.lastModified() > lastModified) {  
        lastModified=file.lastModified();
            returnValue = true;  
        }  
        return returnValue;  
    } 
}


isPropertiesModified方法来判断配置文件的最后修改时间和lastModified 中存储的最后修改时间戳是否一致,一致,不进行重新加载.不一致  重新读取文件内容到内存

以下是测试类

package com.lx.core.util;


import org.springframework.stereotype.Service;


@Service  
public class TaskJob {  

    public void AutoLaunchSend() throws Exception{
   
    String zxq=PropertiesUtil.getProperty("zxq");
   
    System.out.println(zxq);
   
    }
}

1 0