需求
先说下我的需求,首先,我们的服务是个maven的项目,springboot,spring啥的统统都没有用,然后也不打算引入各种配置文件的jar,但是想要在程序运行中,可以动态的修改一些配置,并且程序能识别到,程序里读到的内容也实时变动。
废话不多说了,直接上代码!
代码
首先看一下不能实施的版本啥样
初版,能读到jar包配置文件
private static final ResourceBundle resourceBundle; static{ resourceBundle = ResourceBundle.getBundle("preprocessor-application"); } public static String getKey(String key){ ObjectMapper objectMapper = new ObjectMapper(); String result=resourceBundle.getString(key); return result; }
第二版,可以读到不打到jar包里的配置文件
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.Map; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; public class ResourceUtil { private static final Logger logger = LoggerFactory.getLogger(ResourceUtil.class); /** * 属性文件全名 */ private static final String PFILE ="/home/conf/application.properties"; /** * 对应于属性文件的文件对象变量 */ private static File m_file = null; /** * 属性文件的最后修改日期 */ private static long m_lastModifiedTime = 0; private static ResourceBundle rb; private static BufferedInputStream inputStream; static { try { m_file = new File(PFILE); m_lastModifiedTime = m_file.lastModified(); inputStream = new BufferedInputStream(new FileInputStream(PFILE)); rb = new PropertyResourceBundle(inputStream); inputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static String getKey(String key){ long newTime = m_file.lastModified(); if(newTime > m_lastModifiedTime){ // Get rid of the old properties try { m_lastModifiedTime = m_file.lastModified(); inputStream = new BufferedInputStream(new FileInputStream(PFILE)); rb = new PropertyResourceBundle(inputStream); inputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } String result=rb.getString(key); return result; } }