Spring Boot 如何将抽象类的继承对象作为Java类中的对象字段

rks48beu  于 2022-11-05  发布在  Spring
关注(0)|答案(2)|浏览(127)

我正在创建一个具有以下结构的Spring JPA项目:

public class Pipeline {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private long id;
  private String name;
  private SourceConfig sourceConfig;
  private SinkConfig sinkConfig;
  ...
  ...
}

public abstract class SourceConfig {
  private long id;
  private String name;
}

public abstract class SinkConfig {
  private long id;
  private String name;
}

public KafkaSourceConfig extends SourceConfig {
  private String topic;
  private String messageSchema;
}

public MysqlSourceConfig extends SourceConfig {
  private String databaseName;
  private String tableName;
}

现在,当客户端传递下面的JSON时,程序如何知道要将哪个SourceConfig子类添加到Pipeline对象?

{
    "name": "mysql_to_bq_1",
    "sourceConfig": {
        "source": "MYSQL",

    },
    "sinkConfig": {

    },
    "createdBy": "paul"
}
unftdfkk

unftdfkk1#

您需要指定要使用的类类型,如下所示。因此,不要使用

private SourceConfig sourceConfig;

使用了

private KafkaSourceConfig kafkaSourceConfig;

或者你可以保持它像你有,但万一你想使用一些属性的子类,你必须把它转换成该类类型。
例如:

KafkaSourceConfig kafkaSourceConfig = (KafkaSourceConfig)sourceConfig;

它可以如下所示

if(sourceConfig instanceOf KafkaSourceConfig)
{
KafkaSourceConfig ksc = (KafkaSourceConfig)sourceConfig; 
}
if(sourceConfig instanceOf MysqlSourceConfig)
{
MysqlSourceConfig mysc= (MysqlSourceConfig)sourceConfig; 
}
kqqjbcuj

kqqjbcuj2#

我四处看了一下,了解了Jackson支持的Polymorphic Deserialization,
Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error
实际上,我们必须从某个字段推断出所提供的JSON中引用了哪个子类。
例如,

"sourceConfig": {
  "source": "MYSQL"     
}

这应该调用MysqlSourceConfig的构造函数。因此下面的代码完成了这项工作。

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Data
@JsonTypeInfo(
        use = JsonTypeInfo.Id.NAME,
        property = "source",
        defaultImpl = MysqlSourceConfig.class,
        visible = true)
@JsonSubTypes({
        @JsonSubTypes.Type(value = MysqlSourceConfig.class, name = "MYSQL"),
        @JsonSubTypes.Type(value = KafkaSourceConfig.class, name = "KAFKA"),
})
public abstract class SourceConfig {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Enumerated(value = EnumType.STRING)
    @NotNull
    private Source source;
}

相关问题