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. I created the Maven project as follows:

Bean inheritance in Spring

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 Spring container, I initialize as follows:

OK, now I’m going to declare a common bean for all Clazz objects with the same field schoolName “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:

Bean inheritance in Spring

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 general beanClazz.

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

Result:

Bean inheritance in Spring

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:

Chia sẽ bài viết này ...Share on Facebook
Facebook
0Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

Add Comment