且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Springboot 无法将属性文件映射到变量

更新时间:2022-05-21 02:10:46

this will work and print out CountryData : {MY=[en, zh]}

this will work and print out CountryData : {MY=[en, zh]}

但一定要阅读死侍的答案.

hack 在这里用国家/地区"覆盖默认配置名称应用程序"

the hack is here to override the default configuration name 'application' by 'country'

在示例中,我通过系统属性设置它来完成它,但是通过启动您的应用程序java -jar mycountryapp.jar --spring.config.name=country 应该可以完美运行

in the example, I have done it by setting it via a System property, but starting your application via java -jar mycountryapp.jar --spring.config.name=country should work perfectly

@SpringBootApplication
public class Application {

    static {
      System.setProperty("spring.config.name", "country");
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

@Service
class CountryService {
  private final CountryData countryData;
    public CountryService(CountryData countryData) {
        this.countryData = countryData;
    }

    @EventListener(ApplicationReadyEvent.class)
    public void showCountryDataOnStartup() {
      System.err.println("CountryData : " + countryData.getMap());
    }

}

@Configuration
@ConfigurationProperties(prefix = "entries")
class CountryData {

    Map<String, List<String>> map;

    public Map<String, List<String>> getMap() {
        return map;
    }

    public void setMap(Map<String, List<String>> map) {
        this.map = map;
    }

}