I started studying Spring documentation. I came across parent
attribute explanation, does using parent
attribute between two beans is equivalent to inheritance relationship between these classes?
If so, how to perform method overriding? Also I saw in some context, use of both parent
attribute in XML config file and extends
keyword in bean class. Is it required to specify both springs in order to implement inheritance?
By using the parent attribute of bean, we can specify the inheritance relation between the beans. In such case, parent bean values will be inherited to the current bean.
You can define a parent bean definition as a template and other child beans can inherit the required configuration from the parent bean. When you use XML-based configuration metadata, you indicate a child bean definition by using the parent attribute, specifying the parent bean as the value of this attribute.
An easy way for a bean to inherit another bean, is via the XML-configuration. The parent attritube can be used in the child bean definition inside the bean element, that will indicate the parent bean. Thus, the child bean can use the parent bean's values and override them.
A child bean or inherited bean can inherit its parent bean configurations, properties and some attributes. In additional, the child beans are allow to override the inherited value. See following full example to show you how bean configuration inheritance works in Spring. package com.
parent
in bean configuration signifies configuration inheritance
and not related to Java inheritance. configuration inheritance
saves a lot of code as you do away with repeated XML code. For example, you have following bean with attributes
Class MyBean {
attrib1
attrib2
attrib3
attrib4
}
Say one instance of bean say bean1
just needs attrib1
and attrib2
whereas another say bean2
instance needs all four the attributes.
Lets configure these two beans
<bean id="bean1" class="MyBean">
<property name="attrib1" value="val1" />
<property name="attrib2" value="val2" />
</bean>
<bean id="bean2" parent="bean1">
<property name="attrib3" value="val3" />
<property name="attrib4" value="val4" />
</bean>
Note that bean2
just needed to configure attrib3
and attrib4
. The other two attributes are inherited from bean1
To answer your question:
Does it is required to specify both springs in order to implement inheritance?
No. As mentioned earlier this is not the same as java inheritance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With