java - Spring MVC - 使用 Java 配置读取属性文件
问题描述
由于异常,无法读取 .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";
}
解决方案
如果要在Controller中使用genderOptions作为Map,那么首先需要在gender.properties
文件中以key-value的形式指定。
genderOptions = {M:'Male', F:'Female'}
在控制器中访问它时,您需要进行以下更改,以便让 spring 将其投射到 Map 中。
@Value("#{${genderOptions}}")
private Map<String, String> mapValues;
如果您需要获取 Map 中特定键的值,您所要做的就是在表达式中添加键的名称:
@Value("#{${genderOptions}.M}")
private String maleKey;
推荐阅读
- compression - deflate 是否可以很好地压缩紧密交错的可压缩和不可压缩数据?
- oracle - JBoss 6.4 - Oracle 数据库连接丢失
- javascript - 在 React 中将 onChange 事件从子级传递给父级
- c# - 当在 c# 中启动内部任务时,foreach 或并行 foreach 中的所有元素都不会循环
- python - Anaconda 3:命令行和 Navigator GUI 之间的软件包版本不匹配(仍可更新)
- c++ - 使用 boost::multiprecision cpp_int 进行左移时超出时间限制错误
- java - 使用推土机将值从 java..sql.Struct 转换为 Pojo
- python - NTLM 和 Kerberos 的委派
- c++ - 嵌套循环的 T(n)
- javascript - 如何使用带有框架 vuejs 的 javascript 读取 yaml 文件