在進行web開發時,經常會把一些通用的配置信息以k-v的形式放在config.properties中,比如:數據庫信息,如下圖:
driverClassName=oracle.jdbc.OracleDriver url=jdbc:oracle:thin:@localhost:1521:orcl username=dbcs password=dbcs
然后在代碼中加載config.properties這個配置文件,從中將定義的配置信息一個個取出來,這里介紹兩種方法:
第一種:
private static final String CONFIG_FILE_NAME = "config.properties"; private static Properties p = new Properties(); static String path = null; static { path = FtpConfiguration.class.getResource("/").getPath() + CONFIG_FILE_NAME; try { path = URLDecoder.decode(path, "utf-8"); p.load(new FileInputStream(new File(path))); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 定義構造方法 */ // ftp服務器的ip地址 public static String getIp() { return p.getProperty("ftpIp"); }
如上,這種方法加載了配置文件,但是每一個定義的參數都需要寫一個構造方法去獲取,比如:ftpIp
第二種:
private static Properties props; /* * 靜態代碼塊加載 一次加載多次使用 */ static{ loadProps(); } private synchronized static void loadProps() { logger.info("開始加載properties文件內容... ..."); props = new Properties(); InputStream in = null; try { in = PropertyUtil.class.getResourceAsStream("/config.properties"); props.load(in); } catch (FileNotFoundException e) { logger.error("config.properties文件未找到"); } catch (IOException e) { logger.error(e.getMessage(), e); } finally { try { if(null != in) { in.close(); } } catch (IOException e) { logger.error("config.properties文件流關閉出現異常"); } } logger.info("加載properties文件內容完成..........."); logger.info("properties文件內容:" + props); } /** * 根據配置文件key獲取配置參數值 * @param key * @return */ public static String getProperty(String key){ if(null == props) { loadProps(); } return props.getProperty(key); } public static String getProperty(String key, String defaultValue) { if(null == props) { loadProps(); } return props.getProperty(key, defaultValue); }
這種方式是將方法定義成靜態代碼塊,寫一個統一的get方法,這樣就不需要把config.propeties中每一個定義的參數都寫一個構造方法去獲取,只需要在用到的地方調用
統一的get方法即可,比如:
private static final String WSDL = "rhzx.ws.url"; String wsUrl = PropertyUtil.getProperty(WSDL);
這里推薦使用第二種方式
