jakarta commons configuration 学习笔记
关键字:jakarta, commons, configuration
Runtime Dependencies
运行时需要的一些组件包:- commons beanutils
- commons collections
- commons digester
- commons lang
- commons logging
- xml apis or xerces
- Core
- commons collections
- commons lang
- ConfigurationFactory
- commons logging
- commons digester
- DatabaseConfiguration
- commons logging
- XMLConfiguration, HierarchicalXMLConfiguraion
- xml apis or xerces
- JNDIConfiguration
- commons logging
- ConfigurationDynaBean
- commons beanutils
- commons logging
用ConfigurationFactory 进行配置
portal/
|--src/
|--WEB-INF/
|----config.xml
|----properties/
|------usergui.properties
|----classes/
|------ConfigurationFactoryTest.class
- setConfigurationURL(URL)
- setConfigurationFileName(String)
ConfigurationFactory factory = new ConfigurationFactory();
URL url = new File("WEB-INF/config.xml").toURL();
factory.setConfigurationURL(url);
Configuration config = factory.getConfiguration();
System.out.println(config.getString("colors.background"));
此时config.xml 中其他配置文件的声明要用相对于config.xml 的路径URL url = new File("WEB-INF/config.xml").toURL();
factory.setConfigurationURL(url);
Configuration config = factory.getConfiguration();
System.out.println(config.getString("colors.background"));
<?xml version="1.0" encoding="ISO-8859-1" ?>
<configuration>
<properties fileName="properties/usergui.properties"/>
<!--或 fileName="./properties/usergui.properties"-->
</configuration>
<configuration>
<properties fileName="properties/usergui.properties"/>
<!--或 fileName="./properties/usergui.properties"-->
</configuration>
使用factory.setConfigurationFileName(String) 方法指定配置文件
ConfigurationFactory factory = new ConfigurationFactory();
factory.setConfigurationFileName("WEB-INF/config.xml");
Configuration config = factory.getConfiguration();
System.out.println(config.getString("colors.background"));
此时config.xml 中其他配置文件的声明要用相对于项目的根目录的路径:factory.setConfigurationFileName("WEB-INF/config.xml");
Configuration config = factory.getConfiguration();
System.out.println(config.getString("colors.background"));
<?xml version="1.0" encoding="ISO-8859-1" ?>
<configuration>
<properties fileName="WEB-INF/properties/usergui.properties"/>
</configuration>
<configuration>
<properties fileName="WEB-INF/properties/usergui.properties"/>
</configuration>
!注:如果配置文件的路径填写不正确的话就会遇到如下两个Exception
- org.apache.commons.configuration.ConfigurationFactory.getConfiguration(ConfigurationFactory.java:135) - Exception caught opening stream to URL 表明找不到config.xml
- org.apache.commons.digester.Digester.endElement(Digester.java:1069) - End event threw exception java.lang.reflect.InvocationTargetException 表明找不到config.xml 中声明的其他配置文件