java - 如何使用 Spring Boot 将配置读取到 map

标签 java spring spring-boot yaml

我有一个与配置服务器配合使用并从那里提取配置文件的服务。 配置文件的简化部分示例:

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...

如何将其读取到 map 上?

我尝试过:

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 注入(inject)我的 @Service 类并尝试使用时,所有公共(public)字段(wheels 等)都有值,year ranking 也具有 map 中每个键的值,office 具有空值。如何在不修改 yaml 文件结构且不使用环境手动读取配置的情况下修复它?

最佳答案

我猜,你应该在其他地方寻找错误。我复制了你的类(class)和 Prop : 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 完成。

这些注释不应导致您出现问题。

关于java - 如何使用 Spring Boot 将配置读取到 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76146293/

相关文章:

java - 在tomcat服务器上上传新文件时刷新项目资源文件夹

java - 无法访问 Spring boot application.properties

spring-boot - java.lang.IllegalStateException : Failed to load ApplicationContext Spring Boot + JUnit test 错误

java - Spring 批处理 |读取计数 = 过滤 + 写入?

java - 使用大型地理数据集在 ELKI 上运行 OPTICS 集群

java - 基本GUI程序布局定位

java - JPA - 可选列

java - 更正应用程序的类路径,使其包含单个兼容版本的 oauth2.client.registration.ClientRegistrations

java - 从 SQL Exception 对象获取引发异常的字段和表名称

java - 如何将注释值发送到 @Before 方法中?