Is it possible to extend a pojo class in Spring?

白昼怎懂夜的黑 提交于 2019-12-13 07:06:34

问题


I have a pojo which contains a set of private variables and their setters and getters. This pojo is used extensively across my application. Now, I have to support a scenario where there are multiple pojos and each pojo is a superset of the initial pojo I have. Is it possible that I can extend my original pojo so that I need not change my existing business logic. I am new to spring and I dont know if this is possible. Pojo B should contain everything in pojo A and few more things. Inside the code I will create pojo B objects through pojo A. Basically, some thing similar to inheritance, but with pojos.


回答1:


Typically, you would either aggregate or inherit.

Inherit:

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

class B extends A {
}

Aggregate

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();
    }
}


来源:https://stackoverflow.com/questions/9390581/is-it-possible-to-extend-a-pojo-class-in-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!