首页 > 解决方案 > 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";
}

标签: javaspringspring-mvc

解决方案


如果要在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;

推荐阅读