Home > Spring > Bean definition inheritance in Spring

Bean definition inheritance in Spring

Bean definition inheritance in Spring

Bean definition inheritance in Spring we can achieve by “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.


Example of Bean definition inheritance in Spring:

We are using Ecplise IDE and some required jars to develop below application.

Ecplise IDE : Ecplise Luna

Jars: Placed below jar in “Referenced Libraries” Folder

  1. commons-logging-1.2
  2. spring-beans-5.0.8.RELEASE
  3. spring-context-5.0.8.RELEASE
  4. spring-core-5.0.8.RELEASE
  5. spring-expression-5.0.8.RELEASE

To create this example, we have created 4 files.

  1. India.java
  2. World.java
  3. spring.xml
  4. Client.java

India.java

package beans;
public class India {
private String msg1;
private String msg2;
private String msg3;
public String getMsg1() {
return msg1;
}
public void setMsg1(String msg1) {
this.msg1 = msg1;
}
public String getMsg2() {
return msg2;
}
public void setMsg2(String msg2) {
this.msg2 = msg2;
}
public String getMsg3() {
return msg3;
}
public void setMsg3(String msg3) {
this.msg3 = msg3;
}
}

World.java

package beans;
public class World {
private String msg1;
private String msg2;
public String getMsg1() {
return msg1;
}
public void setMsg1(String msg1) {
this.msg1 = msg1;
}
public String getMsg2() {
return msg2;
}
public void setMsg2(String msg2) {
this.msg2 = msg2;
}
}

spring.xml

<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="wd" class="beans.World">
<property name="msg1" value="Hello World 1"/>
<property name="msg2" value="Hello World 2"/>
</bean>
<bean id="in" class="beans.India" parent="wd">
<property name="msg1" value="Hello India 1"/>
<property name="msg3" value="Hello India 3"/>
</bean>
</beans>

Client.java

package client;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import beans.India;
import beans.World;

public class Client {
public static void main(String[] args) {
ApplicationContext ap=new ClassPathXmlApplicationContext("resources/spring.xml");
World w=(World)ap.getBean("wd");
India i=(India)ap.getBean("in");
System.out.println(w.getMsg1());
System.out.println(i.getMsg1());
System.out.println(i.getMsg2());
System.out.println(i.getMsg3());
}
}

OUTPUT

Hello World 1
Hello India 1
Hello World 2
Hello India 3

Related Topics:-

You may also like :-
Admin
We are group of application developer and admin.We are providing good content of information about IT technology and services .

Leave a Reply

Your email address will not be published. Required fields are marked *