我有一个与配置服务器一起工作的服务,并从那里提取配置文件。 配置文件的简化部分示例:
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 文件的结构并且不使用环境手动读取配置的情况下修复它?
您可以使用 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);
希望这会有所帮助
猜测,你应该去别处寻找错误。我复制了你的课程和道具: 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 完成。
这些笔记不应该导致你的问题。