我有一个与配置服务器配合使用并从那里提取配置文件的服务。 配置文件的简化部分示例:
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}
几点说明:
您
Car
类应该是@ConfigurationProperties
而不是@Configuration
。不要忘记@EnableConfigurationProperties(取决于您的 Spring Boot 版本)。我建议将此类命名为CarProperties
.private Map<String, CarModel> model = new HashMap<>();
- 无需创建实例,这将由 Spring 完成。
这些注释不应导致您出现问题。
关于java - 如何使用 Spring Boot 将配置读取到 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76146293/