如何使用 spring boot 将配置读取到地图

问题描述 投票:0回答:2

我有一个与配置服务器一起工作的服务,并从那里提取配置文件。 配置文件的简化部分示例:

car:
    #name of Map
    model:
        volkswagen:
            year: 1937
            ranking: 2
            office:
                country: germany
                city: wolfsburg
            
        honda:
            year: 1948
            ranking: 3
            office:
                country: japan
                city: tokyo
    #common parameters for all models
    wheels: 4
    #etc...

我怎样才能把这个读到地图上?

我试过:

public class Office
{
    private String country;
    
    private String city;
    
    //setters and getters
}
public class CarModel
{
    private Office office;
    
    private String year;
    
    private int ranking;

    //setters and getters
}
@Configuration
@ConfigurationProperties(prefix = "car")
public class Car
{
    private Map<String, CarModel> model = new HashMap<>();
    
    private int wheels;
    //other common fields and setters and getters for them
    
    
    public Map<String, CarModel> getModel()
    {
        return model;
    }
}

当我将

Car
注入我的@Service类并尝试使用时,所有公共字段(
wheels
等)都有值,
year
ranking
也有地图中每个键的值,但是
office 
具有空值
。如何在不修改 yaml 文件的结构并且不使用环境手动读取配置的情况下修复它?

java spring spring-boot yaml
2个回答
0
投票

您可以使用 ObjectMapper 如下所示

// Loading the YAML file from the /resources folder
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
File file = new File(classLoader.getResource("config.yaml").getFile());

// Instantiating a new ObjectMapper as a YAMLFactory
ObjectMapper om = new ObjectMapper(new YAMLFactory());

// Mapping the employee from the YAML file to the Employee class
CarModel carModel = om.readValue(file, CarModel.class);

希望这会有所帮助


0
投票

猜测,你应该去别处寻找错误。我复制了你的课程和道具: https://github.com/ILyaCyclone/stackoverflow-read-map-76146293

对我来说效果很好:

Car{model={volkswagen=CarModel{office=Office{country='germany', city='wolfsburg'}, year='1937', ranking=2}, honda=CarModel{office=Office{country='japan', city='tokyo'}, year='1948', ranking=3}}, wheels=4}

一些注意事项:

  1. Car
    类应该是
    @ConfigurationProperties
    而不是
    @Configuration
    。不要忘记 @EnableConfigurationProperties(取决于您的 Spring Boot 版本)。我建议命名这个类
    CarProperties
    .

  2. private Map<String, CarModel> model = new HashMap<>();
    - 无需创建实例,这将由 Spring 完成。

这些笔记不应该导致你的问题。

© www.soinside.com 2019 - 2024. All rights reserved.