記錄幾種讀取配置文件的方法,以及配置文件的放置路徑。
1、使用PropertiesLoaderUtils工具類(springframework包提供)
優點:實時加載配置文件,修改后立即生效,不必重啟
配置文件至於classpath中(與class文件放在一起,如果打jar包需打到包內),代碼如下:
private static void springUtil(){ Properties props = new Properties(); while(true){ try { props=PropertiesLoaderUtils.loadAllProperties("param.properties"); for(Object key:props.keySet()){ System.out.print(key+":"); System.out.println(props.get(key)); } } catch (IOException e) { System.out.println(e.getMessage()); } try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();} } }
2、根據文件路徑讀取
優點:配置文件可以放在jar包外面,根據文件路徑尋找配置文件
代碼如下:
public static String readValue(String fileName, String key) { Properties props = new Properties(); String value = null; try { // 配置文件位於當前目錄中的config目錄下 InputStream in = new BufferedInputStream(new FileInputStream("config/" + fileName)); props.load(in); value = props.getProperty(key); } catch (Exception e) { e.printStackTrace(); } return value; }
3、spring加載配置文件的兩種方式
1)按classpath加載(配置文件與class文件放於同一目錄)
初始化Spring代碼:
public static boolean initialize() { if (isInitialize) { return true; } try { appContenxt = new FileSystemXmlApplicationContext("spring.xml"); isInitialize = true; return true; } catch (Exception e) { logger.error("Initialize spring framework failed.", e); return false; } }
配置文件格式:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>jdbc.properties</value> <value>param.properties</value> </list> </property> </bean>
ibatis配置寫法:
<sqlMapConfig>
<settings cacheModelsEnabled="true" enhancementEnabled="true"
lazyLoadingEnabled="true" errorTracingEnabled="true" maxRequests="1024"
maxSessions="1000" maxTransactions="16" useStatementNamespaces="true" />
<sqlMap resource="sqlmap/sqlmap-global.xml" />
<sqlMap resource="sqlmap/sqlmap-memo.xml" />
<sqlMap resource="sqlmap/sqlmap-city.xml" />
</sqlMapConfig>
2)按文件路徑加載(比如配置文件位於當前目錄中的config目錄下)
初始化Spring代碼:
public static boolean initialize() { if (isInitialize) { return true; } try { appContenxt = new FileSystemXmlApplicationContext("file:config/spring.xml"); isInitialize = true; return true; } catch (Exception e) { logger.error("Initialize spring framework failed.", e); return false; } }
配置文件格式:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>file:config/jdbc.properties</value> <value>file:config/param.properties</value> </list> </property> </bean>
ibatis配置寫法:
<sqlMapConfig>
<settings cacheModelsEnabled="true" enhancementEnabled="true"
lazyLoadingEnabled="true" errorTracingEnabled="true" maxRequests="1024"
maxSessions="1000" maxTransactions="16" useStatementNamespaces="true" />
<sqlMap url="file:config/sqlmap/sqlmap-global.xml" />
<sqlMap url="file:config/sqlmap/sqlmap-windcustomcode.xml" />
<sqlMap url="file:config/sqlmap/sqlmap-shiborprices.xml" />
</sqlMapConfig>
