Java讀取properties配置文件

這裏介紹兩種技術:利用spring讀取properties 文件和利用java.util.Properties讀取
(一)利用spring讀取properties 文件
利用org.springframework.beans.factory.support.PropertiesBeanDefinitionReader來讀取屬性文件

構造如下config.properties文件properties代碼<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

userDao.class=com.spring.dao.UserDao 

屬性文件中的"userDao"名稱即是Bean的別名設定,.class用於指定類來源。
然後利用org.springframework.beans.factory.support.PropertiesBeanDefinitionReader來讀取屬性文件
   BeanDefinitionRegistry reg = new DefaultListableBeanFactory();
   PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(reg);
   reader.loadBeanDefinitions(new ClassPathResource("config.properties"));
   BeanFactory factory = (BeanFactory)reg;
   UserDao userDao = (UserDao)factory.getBean("userDao");

(二)利用java.util.Properties讀取屬性文件
1.    String str=File.separator;
        InputStream path=this.getServletContext().getResourceAsStream(str+"WEB-INF"+str+"classes"+str+"password.properties");

        //InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("password.properties");

    /*File filepath=new File(this.getServletContext().getRealPath(str+"WEB-INF"+str+"classes")+str+"password.properties");

        InputStream path=new FileInputStream(filepath);*/
        Properties pros = new Properties();
        try {
            pros.load(path);
        } catch (IOException ex) {
            //System.out.println("file is not exist");
            errorMessage="資源文件不存在";
        }
        System.out.println("username:"+p.getProperty("username")+",password:"+p.getProperty("password"));

2.    import org.springframework.core.io.ClassPathResource;

        ClassPathResource cr = new ClassPathResource("password.properties");//會重新加載spring框架
        Properties pros = new Properties();
        try {
            pros.load(cr.getInputStream());
        } catch (IOException ex) {
            //System.out.println("file is not exist");
            errorMessage="資源文件不存在";
        }

發佈了24 篇原創文章 · 獲贊 7 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章