【问题标题】:Is it possible to extend a pojo class in Spring?是否可以在 Spring 中扩展 pojo 类?
【发布时间】:2012-03-12 12:46:11
【问题描述】:

我有一个 pojo,其中包含一组私有变量及其 setter 和 getter。这个 pojo 在我的应用程序中被广泛使用。现在,我必须支持有多个 pojo 并且每个 pojo 是我拥有的初始 pojo 的超集的场景。是否有可能我可以扩展我原来的 pojo,这样我就不需要改变我现有的业务逻辑。 我是春天的新手,我不知道这是否可能。 Pojo B 应该包含 pojo A 中的所有内容以及更多内容。 在代码中,我将通过 pojo A 创建 pojo B 对象。 基本上,一些类似于继承的东西,但使用 pojos。

【问题讨论】:

  • POJO 是一个普通的旧 Java 对象。它与 Spring 有什么关系?

标签: spring inheritance javabeans pojo


【解决方案1】:

通常,您可以聚合或继承。

继承:

class A {
    private String name;
    public String getName() {
        return name;
    }
}

class B extends A {
}

聚合

public interface A {
    public String getName();
}

public class AImpl implements A {
    private String name;
    public String getName() {
        return name;
    }
}

public class BImpl implements A {
    private A wrapped;
    public BImpl(A wrapped) {
        this.wrapped = wrapped;
    }
    public String getName() {
        return wrapped.getName();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    • 2013-05-21
    • 1970-01-01
    • 2020-12-22
    • 2018-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多