As we discussed earlier a bean definition in configuration metadata can contain constructor arguments, property values etc. Spring framework provides the facility to define a bean definition template which can be used by child bean definitions. To define a template remove class attribute and use abstract attribute to true in bean definition.
Use parent attribute in child definition and pass template bean into it.
Syntax:
Note: We can create template with or without using the class attribute. If we create template using class attribute then corresponding class can’t be instantiated.
Example Explanation:
We have created two beans “HelloWorld” and “HelloJava”. HelloWorld.java and HelloJava.java have one common property msg1. In applicationContext.xml we defined a template helloTemplate which define msg1 property. Then HelloJava and HelloWorld bean use this template as parent and inherits the msg1 property.
Example:
HelloWorld.java
package com.w3schools360.business; /** * This class will be used as a bean class. * @author W3schools360 */ public class HelloWorld { 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; } }
HelloJava.java
package com.w3schools360.business; /** * This class will be used as a bean class. * @author W3schools360 */ public class HelloJava { 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; } }
applicationContext.java
Test.java
package com.w3schools360.business; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { //Get ApplicationContext using spring configuration file. ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); //Get HelloWorld bean object from ApplicationContext instance. HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld"); //Process HelloWorld Object. System.out.println("HelloWorld bean properties: "); System.out.println("Hello " + helloWorld.getMsg1()); System.out.println("Hello " + helloWorld.getMsg2()); //Get HelloJava bean object from ApplicationContext instance. HelloJava helloJava = (HelloJava) context.getBean("helloJava"); //Process HelloJava Object. System.out.println("HelloJava bean properties: "); System.out.println("Hello " + helloJava.getMsg1()); System.out.println("Hello " + helloJava.getMsg2()); } }
Output:
HelloWorld bean properties: Hello Common World. Hello World. HelloJava bean properties: Hello Common World. Hello Java