1. 程式人生 > >讀取配置檔案的幾種方式

讀取配置檔案的幾種方式

1、ResourceBundle讀取.properties 配置檔案

例如,存在一個Messages.properties 配置檔案,根據key讀取value過程如下:

@SuppressWarnings("serial")
public abstract class DispatcherServlet extends HttpServlet {

    private ResourceBundle messagesResource;

    private static final String MESSAGEBASENAME = "Messages";

    /**
     * 將通過此部分讀取資原始檔
     */

    @Override
    public void getMessagesResource() throws ServletException {
        Locale locale = Locale.getDefault();// 根據當前語言環境取得語言編碼
        this.messagesResource = ResourceBundle.getBundle(MESSAGEBASENAME, locale);
    }

this.messagesResource.getString(msgKey);//獲取properties 配置檔案中key值對應的value

}

2、Properties讀取.properties 配置檔案

      //     繼承的是Hashtable,也是根據key讀取value

                FileInputStream fileInputStream=new FileInputStream("Test.properties");
                Properties properties=new Properties();
                properties.load(Messages.properties);
                fileInputStream.close();

        //獲取properties 配置檔案中key值對應的value
        properties.getProperty("key");
        //修改properties 配置檔案中key值對應的value
        properties.setProperty("key","value");

3、   spring中利用ApplicationContext 載入xml檔案

        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        Computer computer = (Computer) applicationContext.getBean("computer");
        computer.run();