1. 程式人生 > >SpringMVC key-value讀取properties配置檔案

SpringMVC key-value讀取properties配置檔案

環境:IDEA 2018.1

1、專案結構如圖

其中,配置的檔案包括User、MainController、info.properties、springmvc.xml,都是手動建立,最後一個在xml configuration file中選為了spring config。

第一步  建立info.properties屬性檔案。

name=123
password=123

因為是測試,所以比較簡單

第二步  建立User ,就是普通的資料類,沒有加入註解。

public class User {
    private String username;

    private String password;

    public void setUsername(String username){
        this.username = username;
    }

    public String getUsername(){
        return username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

嘗試過@value方法,且題主希望在main方法中輸出結果,但static方法不適用,又需要new一個物件再獲取屬性值,幾次獲取到屬性值為null,放棄。

第三步  配置springmvc.xml,為了避免路徑問題,放在了根目錄下。這一步最重要。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd">

    <context:property-placeholder location="classpath:info.properties"/>
    <bean id="user" class="Beans.User">
        <property name="username" value="${name}" />
        <property name="password" value="${password}" />
    </bean>

</beans>

解釋:

  • <context:property-placeholder>載入配置檔案

  • 下面的bean標籤與User對應,id自己定,class定位到類的位置,property對應著屬性,value對應的是在屬性檔案中的key值

容易出現的問題:

  • <context:property-placeholder>無法識別,顯示cannot resolve symbol之類的,我通過加入這三項加以解決的,注意版本號

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd

  • property中name顯示cannot resolve property之類的,用和User中相同的屬性名就能解決,正確情況會有提示

第四步  真正讀取屬性檔案中的值進行顯示,配置MainController,此處就相當於一個測試類。

public class MainController {

    public static void main(String[] args) {
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("springmvc.xml");
        User user=(User) applicationContext.getBean("user");
        System.out.println("name="+user.getUsername());
        System.out.println("age="+user.getPassword());
    }

}

getbean對應的是第四步中的id。嘗試過@Component("user")的方式進行,失敗,顯示不能獲得對應的bean。這個方法結合官方文件和其他部落格,像我一樣的新手建議多參考文件,避免配置不全,理解錯亂。

輸出結果

忽略水印,以上僅供參考。