Java Spring MVC-从yaml文件注入映射
我有一个配置YAML(application.yml)文件,其中包含位置数据:Java Spring MVC-从yaml文件注入映射,java,spring,yaml,Java,Spring,Yaml,我有一个配置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.Configurat
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;
}
}
控制器代码
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启动功能,如果您不使用它,它将不会绑定到应用程序.yml
。最好的解决方案通常是转换为启动。您没有显示控制器本身,也没有说明是否实际使用Spring Boot来运行应用程序。我不使用Spring Boot,只使用常规的Spring MVC。控制器代码为attachedOk。有没有办法使用注释从配置文件加载映射?@zleek不仅仅是通过在应用程序中堆积额外的注释而不采用引导。您想要的特定功能(来自application.yml
的属性解析)是最基本的引导位之一,如果您包含所有必需的部分,那么您无论如何都在进行完全转换。请注意,我从3.0开始就一直在使用Spring,在过去的七年中我一直使用Boot。
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";
}
}