英文:
Spring MVC - Reading properties file using Java Configuration
问题
由于异常无法读取 .properties 文件中的值(org.springframework.expression.spel.SpelEvaluationException: EL1008E: 无法找到属性或字段 'genderOptions')
我已配置属性占位符。我的属性文件中有两个条目(M=MALE,F=FEMALE),我想在提交表单时将其作为复选框的选项列表填充。
@Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Controller
@RequestMapping("/player")
@PropertySource(ignoreResourceNotFound = true, value = "classpath:gender.properties")
public class PlayerController {
@Value("#{genderOptions}")
public Map<String, String> genderOptions;
@RequestMapping("/playerForm")
public String showPlayerForm(Model model) {
Player player = new Player();
model.addAttribute("player", player);
model.addAttribute("genderOptions", genderOptions);
return "player-form";
}
}
英文:
> Values from .properties file could not read due to exception (org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'genderOptions' cannot be found)
I have configured the property place holder. My property file is having two entries (M=MALE, F=FEMALE) I wanted to populate this as a list of options in checkbox while submitting the form.
@Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Controller
@RequestMapping("/player")
@PropertySource(ignoreResourceNotFound = true, value =
"classpath:gender.properties")
public class PlayerController {
@Value("#{genderOptions}")
public Map<String, String> genderOptions;
@RequestMapping("/playerForm")
public String showPlayerForm(Model model) {
Player player = new Player();
model.addAttribute("player", player);
model.addAttribute("genderOptions", genderOptions);
return "player-form";
}
答案1
得分: 1
如果您想在控制器中使用genderOptions
作为Map,则首先需要在gender.properties
文件中以键值对的形式进行指定。
genderOptions = {M:'Male', F:'Female'}
在控制器中访问时,您需要进行以下更改,以便让Spring将其转换为Map。
@Value("#{${genderOptions}}")
private Map<String, String> mapValues;
如果您需要获取Map中特定键的值,您只需将键的名称添加到表达式中:
@Value("#{${genderOptions}.M}")
private String maleKey;
英文:
If you want to use genderOptions as Map in the Controller, then first you need specify it in the form of key-value in gender.properties
file.
genderOptions = {M:'Male', F:'Female'}
And while accessing it in the controller, you need to make following changes in order to let spring cast it in Map.
@Value("#{${genderOptions}}")
private Map<String, String> mapValues;
And if you need to get the value of a specific key in the Map, all you have to do is add the key's name in the expression:
@Value("#{${genderOptions}.M}")
private String maleKey;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论