問題:
需要通過properties讀取頁面的所需樓盤的名稱.為了以后便於修改.
解決:
可以通過spring的 PropertiesFactoryBean 讀取properties屬性,就不需要自己通過jdk的Properties類編寫程序讀取信息.
<!-- 第二種方式是使用注解的方式注入,主要用在java代碼中使用注解注入properties文件中相應的value值 --> <bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="locations"><!-- 這里是PropertiesFactoryBean類,它也有個locations屬性,也是接收一個數組,跟上面一樣 --> <array> <value>classpath:recommondHouse.properties</value> </array> </property> <!-- 設置編碼格式 --> <property name="fileEncoding" value="UTF-8"></property> </bean>
注意: 需要設置fileEncoding,否則會出現亂碼情況,在eclipse中也需要設置properties編碼情況,否則頁面會顯示一堆字符和字母,無法顯示漢字,eclipse中設置如下:
如圖,修改3編碼為utf-8,點擊update即可.
隨后通過@Value注解通過get,set方法注入數據.
package com.fyinqing.util;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("test")
public class PropertiesUtil {
@Value("#{prop.name1}")
private String name1;
@Value("#{prop.name2}")
private String name2;
@Value("#{prop.name3}")
private String name3;
@Value("#{prop.name4}")
private String name4;
public String getName2() {
return name2;
}
public void setName2(String name2) {
this.name2 = name2;
}
public String getName3() {
return name3;
}
public void setName3(String name3) {
this.name3 = name3;
}
public String getName4() {
return name4;
}
public void setName4(String name4) {
this.name4 = name4;
}
public String getName1() {
return name1;
}
public void setName1(String name1) {
this.name1 = name1;
}
public List<String> getNameList(){
List<String> list = new ArrayList<String>();
list.add(name1);
list.add(name2);
list.add(name3);
list.add(name4);
return list;
}
}
測試如下:(只寫了關鍵代碼)
@Autowired
PropertiesUtil propUtil;
@Test
public void test4() {
System.out.println(propUtil.getNameList());
}