Spring Boot YML 配置类继承 [英] Spring Boot YML Config Class Inheritance
问题描述
Spring Boot YML 配置类中是否可以使用继承?如果是这样,那将如何实现?
Is it possible to use inheritance in Spring Boot YML configuration classes? If so, how would that be accomplished?
例如:
@ConfigurationProperties(prefix="my-config")
public class Config {
List<Vehicle> vehicles;
}
类(或接口)Vehicle"有两个实现:Truck 和 Car.所以 YAML 可能看起来像:
And the class (or interface) "Vehicle" has two implementations: Truck and Car. So the YAML might look like:
my.config.vehicles:
-
type: car
seats: 3
-
type: truck
axles: 3
推荐答案
我认为这不可能(至少我不知道).但是,您可以按如下方式设计代码:
I do not think it is possible (at least not that I know of). You could however design your code as follow:
定义一个具有所有属性的对象,我们将其称为 VehicleBuilder
(或工厂,您选择它的名称).VehicleBuilders
从 Yaml 注入.然后,您可以在 @PostConstruct
块中检索每个建造者的车辆.代码:
Define an object with all properties, which we'll call the VehicleBuilder
(or factory, you choose its name).
The VehicleBuilders
are injected from the Yaml.
You can then retrieve each builder's vehicle in a @PostConstruct
block. The code:
@ConfigurationProperties(prefix="my-config")
@Component
public class Config {
private List<VehicleBuilder> vehicles = new ArrayList<VehicleBuilder>();
private List<Vehicle> concreteVehicles;
public List<VehicleFactory> getVehicles() {
return vehicles;
}
public List<Vehicle> getConcreteVehicles() {
return concreteVehicles;
}
@PostConstruct
protected void postConstruct(){
concreteVehicles = vehicles.stream().map(f -> f.get())
.collect(Collectors.<Vehicle>toList());
}
}
建设者:
public class VehicleBuilder {
private String type;
private int seats;
private int axles;
public Vehicle get() {
if ("car".equals(type)) {
return new Car(seats);
} else if ("truck".equals(type)) {
return new Trunk(axles);
}
throw new AssertionError();
}
public void setType(String type) {
this.type = type;
}
public void setSeats(int seats) {
this.seats = seats;
}
public void setAxles(int axles) {
this.axles = axles;
}
}
这篇关于Spring Boot YML 配置类继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!