Bean Definition Inheritance in spring framework

In this article, learn the Bean Definition Inheritance in spring framework. A bean definition can contain configuration information constructor arguments, property values, and container-specific information such as initialization method, static factory method name.
A child bean definition inherits configuration data from a parent definition. The child definition can override some values, or add others.
This allows you to reuse various common properties of various beans.

Example:

 class xadmin {
int x;
int y;
string str;
string msg;
//setter methods
}

without bean definition inheritance

<bean id=”h1” class=”com.xadmin.hello”>
  <property name=”x” value=”10”/>
  <property name=”y” value=”20”/>
  <property name=”str” value=”Hai Guys”/>
  <property name=”msg” value=”hello guys”/>
<bean>
<bean id=”h2” class=”com.xadmin.Hello”>
  <property name=”x” value=”10”/>
  <property name=”y” value=”30”/>
  <property name=”str” value=”Hai Guys”/>
  <property name=”msg” value=”hello guys”/>
<bean>

with bean definition inheritance

<bean id=”baseHello” class=”com.xadmin.hello” abstract=”true”>
  <property name=”x” value=”10”/>
  <property name=”str” value=”Hai Guys”/>
<bean>
<bean id=”h1” parent=”basehello”>
  <property name=”y” value=”20”/>
  <property name=”str” value=”Hai Guys”/>
<bean>
<bean id=”h2” parent=”basehello”>
  <property name=”y” value=”30”/>
  <property name=”str” value=”Hai Guys”/>
<bean>

What is Externalizing bean properties and how to implement it.

This allows you to place the bean property values in a separate property file instead of hard-coding the values in the spring configuration document.

Steps:

  • write one or more property files and place them in project folder directly
    oracle.properties
    oracle.dc=some drive class
    oracle.url=some url
  • Refer the keys in xml as follows:
    <property name=”dc” value=”${oracle.dc}”/>
  • To Externalize bean properties, you have to register property placeholder configuration bean in spring configuration documenet as follows.

<bean class=”org.springframework.beans.factory.config.propertyPlaceholderConfiguration”>
<property name=”location”>
<list>
<value> oracle.properties</value>
<value> mysql.properties</value>
<value> common.properties</value>
<list>
</property>
<bean>

What is Accessing Message bundles

  1. When developing any web application you will write various message bundles to support multiple languages.
  2. When you want to access properties from message bundles with the help of spring, you need to do the following steps:
    1. write one or more message bundles to support multiple languages
      Basename Language code country code.properties
      Basename LanguageCode properties
    2. Message.properties(English)Un.required=Username is Required(English)
      Errors.required={0} is Required (English)
      Errors.rang={0} length must be between {1} and {2} (English)

3. Message hi.properties (Hindi)

Un.required=Username is Required(hindi)
Errors.required={0} is Required (hindi)
Errors.rang={0} length must be between {1} and {2} (hindi)
Access the properties of message bundles bundles using following methods of Application Context
getMassage(String key, object [] args, Locale};
getMassage(String key, object [] args, String defaultMassage, Locale};

Example:

String m1=ctx.getMessage(“un.required”, null, new locale(“h1”));
String m2=ctx.getMessage(“errors.required”, new object[] {email id”} new locale(“en”));
String m3=ctx.getMessage(“errors.range”, new object[] username”,”5”, 10”) new locale(“hi”));
String m4=ctx.getMessage(“pw.required”,null,new locale(“hi”));

Register the bean called Resource bundleMessageSource with spring container by specifying the followiung in spring configuration document

<bean id=”messageSource” class=”org.springframework.context.support.Resource Bunbdle MessageSource”>
<property name=”basename” value=”message”/>
<bean>

Example for the message bundle.
File required:

  1. xadmin.java
  2. TestBean.java
  3. Message.properties
  4. Messages.hi.properties
  5. xadmin.xml

xadmin.java

Package com.xadmin.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.Support.ClassPathXmlApplicationContext;

public class xadmin
{
public static void main(String args[])
{
ApplicationContext ctx=new ClassPathXmlApplicationContext(“xadmin.xml”);
TestBean tb=(TestBean)ctx.getBean(“TestBean”);
tb.showEnglish();
tb.showHindi();
}

TestBean.java

package com.xadmin.spring

import java.util.Locale;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.context.ApplicationContext;

public class TestBean {

@Autowired
ApplicationContext ctx=null;

void showEnglish() { 
String m1=ctx.getMessage(“username.required”, null, null);
System.out.println(m1);
String m2=ctx.getMessage(“password.required”, new object[]{password}, null);
System.out.println(m2);
}

void showHindi() { 
String m1=ctx.getMessage(“username.required”, null, null Locale (“hi”);
System.out.println(m1);
String m2=ctx.getMessage(“password.required”, new object[]{password}, null Locale(“h1”);
System.out.println(m2);
}
}

Messages.properties

Username.required=Username is Required.
Password.required={0} is Required
Error.min={0} must be min:{1}
Error.max={0} must be max:{1}

Messages.hi.properties

Username.required=Username is Required. {IN HINDI}
Password.required={0} is Required IN HINDI}
Error.min={0} must be min:{1} IN HINDI}
Error.max={0} must be max:{1} IN HINDI}

xadmin.xml

<beans>
<context:annnotion-config/>

<bean id=”messageSource” class=”org.springframework.context.support.Resource.BundleMessageSource”>
<property name=”basename” value =”message”/>
<bean>

<bean id=”textBean” class=”class.jtcindia.spring.TestBean”/>
<beans>

using property Editors

  • property Editors are used to edit the property values.
  • You can do the following using property editors
    • Convert the values from one data type to another data type
    • Convert the value from one format to another format.

Example

class Hello {
int x;
Double y;
String str;

}
<bean id=”h” class=”Hello”>
 <property name=”x” value =”99”/>
<property name=”y” value =”99.99”/>
<property name=”str” value =”hello guys”/>
</bean>

For simple data types, there are many built-in property editors available. For your custom data types, you have to develop custom property editors.

Steps to develop and register custom property editors.

Write your own editors class by extending property editor support class available in java. Beans package.
Override the following method in custom editor class
public void setAsText(String text)
Write the required conversion logic inside setAsText() method.
Register the Custom property editors with spring container as follows:

<bean class=”org.springframework.beans.factory.config.customeditorConfigurer”>
<property name=”customEditors”>
<map>
<entry key=”java.util.List” value=”com.xadmin.spring.listEditor”/>
<entry key=”com.xadmin.spring.Fee” value=”com.xadmin.spring.Feeeditor”/>
<map>
<property>
<bean>

Example File required:

  1. Xadmin.java
  2. Student.java
  3. StudentId.java
  4. StudentIdEditor.java
  5. Fee.java
  6. FeeEditor.java
  7. xadmin.xml
  8. ListEditor.java

Xadmin.java

package.com.xadmin.spring;
import com.springframework.context.application.Context;
import com.springframework.context.support.*;

public class Xadmin{
public static void main(String args[]);
ApplicationContext ctx=new ClassPathXmlApplicationContext(“xadmin.xml”);
Student stu=(Student)ctx.getBean(“Student”);
System.out.println(stu.getsid().getBid());
System.out.println(stu.getsid().getsid());
System.out.println(stu.getSname());
System.out.println(stu.getPhone());
System.out.println(stu.getFee().getFeeBal());
System.out.println(stu.getFee().getFeepaid());
System.out.println(stu.getFee().getTotalFee());
System.out.println(stu.getEmails());
System.out.println(stu.getPhones());
}
}

Student.java

package com.xadmin.spring;

import java.util.list;

public class Student {
StudentId sid;
String sname;
Long phone;
Fee fee;
List<string> emails;
List<Long> phones;

// setters and getters
}

StudentIDEditor.java

package com.xadmin.spring;
import java.beans.propertyEditorSupport;

public class studentIDEditor extends propertyEditorSupport {
public void setAsText{ String txt) {
String p1=txt.substring(o,3);
String p2=txt.substring(94);
StudentID sid=new studentId(Interger.parseInt(p2),p1);
this.setValue(sid);
}
}

StudentID.java

package com.xadmin.spring;
public class studentID {
string bid;
int sid;
public studentID(int sid, string bid)
{
this.sid=sid;
this.bid=bid;

}
//setters and getters
}

Fee.java

package com.xadmin.spring;
public class Fee {
double totalfee;
double feePaid;
double feeBal;

public Fee(double totalFee, double feePaid, double feeBal) {
Super();
this.totalFee=totalFee;
this.feepaid=feePaid;
this.feeBal=feeBal;
}
//setter and getters

}

FeeEditor.java

package com.xadmin.spring;
import java.beans.propertyEditorSupport;

public class FeeEditor extends propertyEditorSupport {
public void setAsText{ String txt) {
String str[]= txt.split(“,”);
Fee fee= new Fee(Double.parseDouble(str[0],Double.parseDouble(str[1]), double parseDouble(str[2]);
this.setValue(fee);
}
}

ListEditor.java

package com.xadmin.spring;
import java.beans.propertyEditorSupport;

public class ListEditor extends propertyEditorSupport {
public void setAsText{ String txt) {
String str[]= txt.split(“,”);
List list=Arrays.asList(str);
this.setValue(list);
}
}

Xadmin.xml

<beans>
<context:annnotion-config/>
<bean class=”org.springframework.beans.factory.config.customeditorConfigurer”>
<property name=”customEditors”>
 <map>
 <entry key=”com.xadmin.spring.studentID” >
<value>com.xadmin.spring.StudentIDEditor</value>
</entry>

 <entry key=”com.xadmin.spring.Fee”>
< value>com.xadmin.spring.Feeeditor</value>
<entry>

 <entry key=”java.util.list”>
< value>com.xadmin.spring.listEditor</value>
<entry>
<map>

</property>
</bean>

Events and Listeners

  • Event Handling mechanism is provided with spring container called application context.
  • Application context container handles two types of events:
    • Standard or system events
    • Custom or application events

Standard Events
Spring provides the following standard events

  • Context standard event
  • Context refreshed event
  • Context stopped event
  • Context closed event
  • Context started event will be published when the application context is started using the start() method on the configurable application context interface.
  • The ContextRefreased event will be published when the application context is initialized or refreshed using refresh() method on the configurable application context interface.
  • Context Stopped event will be published when the application context is stopped using stop() method on the configurable application context interface.
  • Context closed event will be published when the application context is closed using a close() method on the configuring application context interface.

Conclusion:
All this article is about the Spring -Bean Definition Inheritance in spring framework. Spring Bean definition inheritance has nothing to do with Java class inheritance but the inheritance concept is the same.
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. Please, feel free to drop a comment in the comment box below if you have a doubt regarding the topic or you want to share more information about the topic. Happy Learning !!

 

Leave a Reply

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