[英]Spring MVC - inject map from yaml file
我有一个包含位置数据的配置 YAML (application.yml) 文件:
locations:
countries:
PL: Poland
DE: Germany
UK: UK
RU: Russia
我想加载它,以便它在 html 选择字段中可用。
我创建了以下类:
package eu.test.springdemo.model;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.Map;
@ConfigurationProperties(prefix = "locations")
public class CountryOptions {
private Map<String, String> countries;
public Map<String, String> getCountries() {
return countries;
}
public void setCountries(Map<String, String> countries) {
this.countries = countries;
}
}
然后我通过@Autowire 将 CountryOptions 注入控制器。 但是,控制器中的国家/地区列表为空。
应用程序的配置由包含以下注释的类提供:
@Configuration
@EnableWebMvc
@EnableConfigurationProperties(CountryOptions.class)
@ComponentScan(basePackages="eu.test.springdemo")
public class DemoAppConfig implements WebMvcConfigurer {
控制器代码
package eu.test.springdemo.mvc;
import eu.test.springdemo.model.CountryOptions;
import eu.test.springdemo.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("/")
public class HelloController {
@Autowired
CountryOptions countryOptions;
@GetMapping("/")
public String showPage() {
return "main-menu";
}
@GetMapping("/showForm")
public String showForm(Model model) {
model.addAttribute("student", new Student());
model.addAttribute("countries", countryOptions.getCountries());
return "helloworld-form";
}
}
那么 - 为什么不从 yaml 文件创建国家列表的任何想法?
@ConfigurationProperties
是 Spring Boot 的一个特性,如果你不使用它,它不会绑定到application.yml
。 最好的解决方案通常是转换为Boot。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.