java中讀取配置文件

一、使用org.apache.commons.configuration

需要使用的是jar包:commons-collections-3.2.1.jar、commons-configuration-1.10.jar、commons-lang-2.6.jar和commons-logging-1.2.jar。

可以讀取的配置文件:xml和properties

1、讀取xml文件

使用到的config.xml內容如下:

  1. <Account type="by0003">    
  2.      <code>100001</code>   
  3.      <pass>123</pass>   
  4.      <name>李四</name>    
  5.      <money>1000000.00</money>    
  6. </Account>
讀取配置文件:

  1. import org.apache.commons.configuration.Configuration;  
  2. import org.apache.commons.configuration.ConfigurationException;  
  3. import org.apache.commons.configuration.XMLConfiguration;  
  4. public class xmlLoaderTest {  
  5.   
  6.     public static void main(String[] args) throws ConfigurationException{  
  7.        Configuration config = new XMLConfiguration("com/styspace/config.xml");  
  8.        String name = config.getString("Account.name");  
  9.        System.out.println("name:" + name);  
  10.     }  

需要注意的是config.getString(“Account.name”)中的參數是Account.name,這個參數是XPath格式的,而且不能包含xml中的根元素。


2、讀取properties文件

使用到的config.properties文件內容如下:

  1. timout=15.52  
  2. interactive=true  
  3. color=red  
  4. speed=50  
  5. name=Default User

第一種方式:

  1. import org.apache.commons.configuration.Configuration;  
  2. import org.apache.commons.configuration.ConfigurationException;  
  3. import org.apache.commons.configuration.PropertiesConfiguration;  
  4.   
  5. public class peropertiesLoaderTest {  
  6.   
  7.     public static void main(String[] args) throws ConfigurationException{  
  8.        Configuration config = new PropertiesConfiguration("com/styspace/config.properties");  
  9.        String name = config.getString("name");  
  10.        System.out.println("name:" + name);  
  11.     }  
  12. }  

  1. import org.apache.commons.configuration.Configuration;  
  2. import org.apache.commons.configuration.ConfigurationException;  
  3. import org.apache.commons.configuration.PropertiesConfiguration;  
  4.   
  5. public class peropertiesLoaderTest {  
  6.   
  7.     public static void main(String[] args) throws ConfigurationException{  
  8.        Configuration config = new PropertiesConfiguration("com/styspace/config.properties");  
  9.        String name = config.getString("name");  
  10.        System.out.println("name:" + name);  
  11.     }  
  12. }

第二種方式: 使用java.util.Properties讀取

  1. import java.io.IOException;  
  2. import java.io.InputStream;  
  3. import java.util.Properties;  
  4.   
  5. public class PropertiesTest {  
  6.     public static void main(String[] args){  
  7.         PropertiesTest pt = new PropertiesTest();  
  8.         try {  
  9.             pt.getProperties();  
  10.         } catch (IOException e) {  
  11.             // TODO Auto-generated catch block  
  12.             e.printStackTrace();  
  13.         }  
  14.     }  
  15.       
  16.     private void getProperties() throws IOException {  
  17.         InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("com/styspace/config.properties");  
  18.         System.out.println("begin!!!");  
  19.         Properties properties = new Properties();  
  20.         try{  
  21.             properties.load(inputStream);  
  22.         }catch (IOException ioE){  
  23.             ioE.printStackTrace();  
  24.         }finally{  
  25.             inputStream.close();  
  26.         }  
  27.         System.out.println("name:"+properties.getProperty("name"));  
  28.     }  


需要注意的是hetClassLoader().getResourceAsStream()的參數是項目根目錄下的路徑,儘管config.properties是該該類文件在相同的目錄下,但是不能寫成getClassLoader().getResourceAsStream("config.properties"),這樣程序會報錯,得到的InputStream是null值。


ClassLoader()和URLClassLoader()區別:ClassLoader()只能查找src目錄下的文件,而URLClassLoader()則能查找任意目錄下的文件。


三、spring中配置文件的讀取

1、ClassPathXmlApplicationContext:從類路徑中加載。

2、FileSystemXmlApplicationContext:從文件系統加載。

3、XmlWebApplicationContext:web系統中加載


1、使用bean工廠獲取bean

  1.  BeanFactory factory = null//聲明  
  2.       
  3.     ClassPathResource resource = new ClassPathResource("spring.xml");//類路徑  
  4.     factory= new XmlBeanFactory(resource);   
  5.       
  6.     FileSystemResource fileSystemResource = new FileSystemResource("D:\\Ncode\\mcode\\sday02\\src\\spring.xml");//文件路徑  
  7.     factory= new XmlBeanFactory(fileSystemResource);   
  8.       
  9.     //XmlBeanFactory(參數可以是resource或者fileSystemResource等  
  10.     //但是不能是 res 原因可以查看:文檔Part III. Core Technologies 6. Resources  
  11.     //中6.2 The Resource interface 有關isOpen方法的說明);  
  12.     //InputStreamResource res = new InputStreamResource(new FileInputStream("D:\\Ncode\\mcode\\sday02\\src\\spring.xml"));//系統路徑  
  13.   
  14.     HelloService helloService = factory.getBean("helloServiceImpl", HelloServiceImpl.class);  
  15.     helloService.sayHello();
2、使用上下文(Context)

上下文更加高級:提供文本信息解析工具,包括對國際化支持;提供載入文件資源的通用方法,如圖片;可以向註冊爲監聽器的bean發送事件。在很少的情況下,使用BeanFactory.

  1. //從文件系統  
  2.     ApplicationContext context = new FileSystemXmlApplicationContext("file:D:\\Ncode\\mcode\\sday02\\src\\spring.xml");  
  3.     //從類路徑  
  4.     ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring.xml");  
  5.       
  6.     HelloService helloService =  context.getBean("helloServiceImpl", HelloServiceImpl.class);  
  7.     helloService.sayHello();
3、在web應用中使用

3.1、使用XmlWebApplicationContext

  1. XmlWebApplicationContext context = new XmlWebApplicationContext();   
  2. //默認的路徑/WEB-INF/applicationContext.xml  
  3. //applicationContext.xml文件名稱 可以任意起  
  4. //重新設置路徑  
  5. //context.setConfigLocations(new String[] {"/WEB-INF/classes/applicationContext.xml"});   
  6. //設置ServletContext上下下文爲web應用程序的上下文  
  7. context.setServletContext(getServletContext());  
  8. //刷新  
  9. context.refresh();  
  10. //根據id名稱獲取  
  11. HelloDao helloDao = context.getBean("helloDaoImpl", HelloDaoImpl.class);  
  12. //執行helloDao對象的方法  
  13. helloDao.sayHello();
3.2、使用WebApplicationContextUtils工具類

  1. //直接採用getWebApplicationContext(getServletContext()) 獲取context對象  
  2. WebApplicationContext  context=   
  3. WebApplicationContextUtils.getWebApplicationContext(getServletContext());  
  4. //context = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());  
  5. System.out.println(context);  
  6. HelloDao helloDao = context.getBean("helloDaoImpl", HelloDaoImpl.class);  
  7. helloDao.sayHello() 


兩者的區別是:

1、當採用getWebApplicationContext(getServletContext())獲取context對象的時候,輸出的context對象爲null  所以在使用

context.getBean("helloDaoImpl", HelloDaoImpl.class);會出現空指針的異常

   2、當採用getRequiredWebApplicationContext(getServletContext());獲取context對象的時候 會出現如下bug

java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered



轉載自: http://blog.csdn.net/stypace/article/details/38414871

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章