首先,你有將屬性文件添加到您的上下文配置中:
@PropertySource(name = "questions", value = "classpath:question.properties")
public class AppConfig {
...
}
我在示例中使用了classpath:
前綴(即文件將位於類路徑的根目錄中),但您可以使用file:
來指定絕對路徑。請注意,該來源的名稱被指定爲questions
。我們將來需要它。
第二個,創建數據容器類。當然,你可以使用Map<String, String>
來存儲你的問題,但類會更加方便:
public class Quest{
private String number;
private String text;
//getters and setters
....
}
三,在控制器和負荷數和值獲取財產來源:
@Controller
public class MyController {
@Autowired
private ConfigurableEnvironment environment;
@RequestMapping("/mymapping")
public String method(ModelMap model){
List<Quest> questList = loadQuestList();
model.addAttribute("questList", questList);
return "myview";
}
private List<Quest> loadQuestList(){
ResourcePropertySource source =
(ResourcePropertySource)environment.getPropertySources().get("questions");
//first get all names of questions like 'Quest1','Quest2' etc
List<String> nameList = new ArrayList<String>();
for(String name : source.getPropertyNames()){
if(!name.endsWith("Text")){
nameList.add(name);
}
}
//unfortunately, default properties are unsorted. we have to sort it
Collections.sort(nameList);
//now, when we have quest names, we can fill list of quests
List<Quest> list = new ArrayList<Quest>();
for(String name : nameList){
String number = source.getProperty(name);
String text = source.getProperty(name+"Text");
Quest quest = Quest();
quest.setNumber(number);
quest.setText(text);
list.add(quest);
}
return list;
}
}
的可能的複製[更好的方式來表示數組在java屬性文件](http://stackoverflow.com/questions/7015491/better-way-to-represent-array-in-java-properties-file) – Prashant
你特別想春天做到這一點或任何其他方法(不使用彈簧)也很好? – Suyash
你最終想得到什麼:'Map'或不同的'列表'帶數字和文本? –