gpt4 book ai didi

spring-boot - Spring Boot YML Config类继承

转载 作者:行者123 更新时间:2023-12-04 03:16:45 27 4
gpt4 key购买 nike

在Spring Boot YML配置类中是否可以使用继承?如果是这样,那将如何实现?

例如:

@ConfigurationProperties(prefix="my-config")
public class Config {
List<Vehicle> vehicles;
}

类(或接口(interface))“Vehicle”有两个实现:Truck 和 Car。所以 YAML 可能看起来像:

my.config.vehicles:
-
type: car
seats: 3
-
type: truck
axles: 3

最佳答案

我认为这是不可能的(至少我不知道)。但是,您可以按如下方式设计代码:

将属性注入(inject)到 Builder 对象中

定义一个具有所有属性的对象,我们将其称为 VehicleBuilder(或工厂,您可以选择其名称)。VehicleBuilders 从 Yaml 注入(inject)。然后,您可以在 @PostConstruct block 中检索每个构建器的车辆。代码:

@ConfigurationProperties(prefix="my-config")
@Component
public class Config {
private List<VehicleBuilder> vehicles = new ArrayList<VehicleBuilder>();
private List<Vehicle> concreteVehicles;

public List<VehicleBuilder> getVehicles() {
return vehicles;
}

public List<Vehicle> getConcreteVehicles() {
return concreteVehicles;
}

@PostConstruct
protected void postConstruct(){
concreteVehicles = vehicles.stream().map(f -> f.get())
.collect(Collectors.<Vehicle>toList());
}
}

build 者:

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 - Spring Boot YML Config类继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40367935/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com