Bean inheritance in Spring

In Java, we inherit one object using the abstract keyword, Spring also supports us to do the same thing in itself. This tutorial will show you how to use bean inheritance in Spring.

OK, first we need to have a Maven project to work on. I created the Maven project as follows:

In particular, the Spring framework dependency is as follows:

Clazz class:

Application class:

To be able to use inheritance, at least the beans that are declared in the Spring container must have a common feature. So in the Clazz class above, I declare a field that is common to all bean fields, schoolName.

In the Spring container, I initialize as follows:

OK, now I’m going to declare a common bean for all Clazz objects with the same schoolName field as “Tam Quan Nam” as follows:

In order for the bean clazzA and bean clazzB to use the common bean, we need to declare the parent attribute with the id of the generic bean, in the declaration of the bean clazzA and bean clazzB, as follows:

Now if you run the program, you will see the results as follows:

As you can see, although we do not declare the schoolName field for the clazzA bean, the clazzA bean still has the field name because it is inherited from the bean generalClazz.

It should also be added that in this case our bean generalClazz is also initialized in Spring’s container and we can retrieve it:

Result:

If you want it to be just an abstract as defined in Java, which means that it cannot be initialized in Spring’s container, we can declare the abstract = “true”:

In this case, if you run the code above, will encounter the following error:

Add Comment