spring boot—解析动态yaml并使用注解将它们Map到java对象

u5rb5r59  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(443)

我想解析具有动态属性的yaml文件。所以,我有不同国家的yaml文件-荷兰.yml,美国.yml,英国.yml…等等
文件的内容如下所示-

netherlands:
  name: netherlands
  type: country
  location:
    latitude: aaa
    longitude: bbb
  amsterdam:
    name: amsterdam
    type: city
    latitude: xxx
    longitude: yyy
  rotterdam:
    name: rotterdam
    type: city
    latitude: ddd
    longitude: ggg 
  hague:
    name: hague
    type: city
    latitude: kkk
    longitude: lll

我想在我的代码中以这种方式解析和读取它-

@country(name="netherlands")
Country country;

country.getAmsterdam.getLatitude()

我使用的是springboot和java11。如何使用注解来实现这一点?我想我需要为每个国家写一个自定义注解。但主要问题是,每个国家的城市名称都是动态的,城市数量也会因国家而异。另外,城市也可以在yaml中添加。我能够编写一个代码来解析yaml并将其Map到我的对象。但我现在看到的是,它需要Map到一个具有固定属性的类,这不是我的情况。这是我写的代码,但它不符合我的目的。

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
File file = new File(classLoader.getResource("netherlands.yml").getFile());
ObjectMapper om = new ObjectMapper(new YAMLFactory());
Country country = om.readValue(file, Country.class);

    public class Country{    
    private String name ;
    private String type;
    private Location location;    
    // Here I need the dynamic attributes for my cities

   }

我查了很多文章,但找不到这样的例子。你能提出一个实现这个目标的方法吗?非常感谢你的帮助。

3xiyfsfu

3xiyfsfu1#

如果您的.yml文件在运行时不会更改,您可以考虑使用@configurationproperties spring注解。
使用它可以创建@configuration类,如下所示:

@Configuration
@Data
public class CountryConfiguration {

    @Bean
    @ConfigurationProperties(prefix = "netherlands")
    private final Country netherlands;

    ...
}

您还需要使用本答案中描述的其他configs支持,以允许在@configurationproperties注解中看到您的netherlands.yml和其他文件。
关于动态字段生成-这是不可能的,因为java是静态类型化语言。如果你不知道城市的名字,你就不能和城市一起工作,这没有任何意义。因此,我建议您将.yml文件的结构更改为:

netherlands:
  name: netherlands
  type: country
  location:
    latitude: aaa
    longitude: bbb
  cities:
    - amsterdam:
      ....

如果不可能的话。当你可以考虑使用 private final Map<String, Object> netherlands .

相关问题