代码如下:
package com.yanek.base; import org.apache.commons.configuration.CompositeConfiguration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; public class PropManager { /** * @param args */ public static void main(String[] args) { String jdbcUrl = PropManager.getInstance().getProperty("jdbc.cms.url"); String jdbcUsername = PropManager.getInstance().getProperty("jdbc.cms.username"); String jdbcPassword = PropManager.getInstance().getProperty("jdbc.cms.password"); System.out.println("jdbcUrl:"+jdbcUrl); System.out.println("jdbcUsername:"+jdbcUsername); System.out.println("jdbcPassword:"+jdbcPassword); System.out.println(PropManager.getInstance()); System.out.println(PropManager.getInstance()); } private PropManager() { } private static PropManager propManager; public synchronized static PropManager getInstance() { if (propManager == null) { propManager = new PropManager(); } return propManager; } public static CompositeConfiguration config = new CompositeConfiguration(); static { try { config.addConfiguration(new PropertiesConfiguration("jdbc.properties")); } catch (ConfigurationException e) { e.printStackTrace(); } } public String getProperty(String key) { return config.getString(key); } }
测试输出:
jdbcUrl:jdbc:mysql://127.0.0.1:3306/easycms?characterEncoding=UTF8
jdbcUsername:root
jdbcPassword:root
com.yanek.base.PropManager@174cc1f
com.yanek.base.PropManager@174cc1f
使用的包: commons-configuration-1.6.jar
几点说明:
1. 采用了单态设计模式,
2.属性文件在classpath目录下.
3. 采用commons-configuration-1.6.jar来读取属性文件
jdbc.properties文件:
jdbc.cms.url=jdbc:mysql://127.0.0.1:3306/easycms?characterEncoding=UTF8
jdbc.cms.username=root
jdbc.cms.password=root