【发布时间】:2020-11-07 21:35:29
【问题描述】:
我目前正在对继承的 Spring Boot 应用程序进行开发,其中一部分是发送一个 API POST 请求,其中包含足球比赛是否结束的布尔值 (resulted)。我注意到这个类的设计是这样的:
//parent class
public class Fixture {
private final FixtureType type;
private final Team homeTeam;
private final Team awayTeam;
public Fixture(@JsonProperty("type") final FixtureType type,
@JsonProperty("homeTeam") final Team homeTeam,
@JsonProperty("awayTeam") final Team awayTeam
) {
this.type = type;
this.homeTeam = homeTeam;
this.awayTeam = awayTeam;
}
public boolean isResulted() {
return false;
}
/*
other methods
*/
}
//child class
public class Result extends Fixture {
private final Outcome outcome;
public Result(@JsonProperty("type") final FixtureType type,
@JsonProperty("homeTeam") final Team homeTeam,
@JsonProperty("awayTeam") final Team awayTeam,
@JsonProperty("outcome") final Outcome outcome) {
super(type, homeTeam, awayTeam);
this.outcome = outcome;
}
@Override
public boolean isResulted() {
return true;
}
/*
other methods
*/
}
在 Swagger 文档中,请求指定 "resulted": true 需要是 JSON POST 请求中的一个字段。现在我可以将该字段添加到构造函数中,但这意味着更改调用此构造函数的大量测试和代码。我的解决方案是在构造函数本身中调用isResulted() 方法。我以前从未这样做过,但这有效。从长远来看,下面的这种设计是否会产生问题?
public class Result extends Fixture {
private final boolean resulted;
public Result (){
super();
resulted = isResulted();
}
@Override
@JsonProperty("resulted")
public boolean isResulted() {
return true;
}
}
【问题讨论】:
标签: java spring-boot constructor jackson jackson-databind