簡體   English   中英

Spring MVC - 從 yaml 文件注入地圖

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM