gpt4 book ai didi

java - Spring MVC - 使用 Java 配置读取属性文件

转载 作者:行者123 更新时间:2023-12-02 08:46:38 25 4
gpt4 key购买 nike

Values from .properties file could not read due to exception (org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'genderOptions' cannot be found)

我已经配置了属性占位符。我的属性文件有两个条目(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:'男', F:'女'}

在 Controller 中访问它时,您需要进行以下更改,以便让 spring 将其转换到 Map 中。

@Value("#{${genderOptions}}")
private Map<String, String> mapValues;

如果你需要获取Map中特定键的值,你所要做的就是在表达式中添加键的名称:

@Value("#{${genderOptions}.M}")
private String maleKey;

关于java - Spring MVC - 使用 Java 配置读取属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61040588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com