Sunday, April 27, 2014

Injecting inner beans in Spring

Similar to Java which provides defining inner class inside another class, Spring IOC provides defining a bean inside another bean.This will be useful when a bean is declared as property in another bean.

Let us see the inner bean in action

Lets say i have an Employee bean and employee has an address object declared as a field in Employee object.

package com.ramesh.domain;

public class Employee {

 private int id;
 private String name;
 private long salary;
 private Address address;

 public int getId() {
  return id;

 public void setId(int id) { = id;

 public String getName() {
  return name;

 public void setName(String name) { = name;

 public long getSalary() {
  return salary;

 public void setSalary(long salary) {
  this.salary = salary;

 public Address getAddress() {
  return address;

 public void setAddress(Address address) {
  this.address = address;


As shown above employee as a Address field.Lets see the Address bean

package com.ramesh.domain;

public class Address {

 private String street;
 private String pinCode;
 private String city;

 public String getStreet() {
  return street;

 public void setStreet(String street) {
  this.street = street;

 public String getPinCode() {
  return pinCode;

 public void setPinCode(String pinCode) {
  this.pinCode = pinCode;

 public String getCity() {
  return city;

 public void setCity(String city) { = city;


Now configure the spring-context.xml 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
 xmlns:xsi="" xmlns:mvc=""

 <bean id="employee" class="com.ramesh.domain.Employee">
  <property name="id" value="844" />
  <property name="name" value="Ramesh M" />
  <property name="salary" value="85000" />
  <property name="address">
   <bean class="com.ramesh.domain.Address">
    <property name="street">
     <value>Embassy Golflinks Business Park Street</value>
    <property name="city">
    <property name="pinCode">



Since we completed the configuration lets test 

package com.ramesh;

import org.springframework.context.ApplicationContext;

import com.ramesh.domain.Employee;

public class MainApp {

 public static void main(String[] args) {
  ApplicationContext appContext = new ClassPathXmlApplicationContext(
  Employee employee = (Employee) appContext.getBean("employee");

  // displaying employee name

  // displaying inner bean address details



The output:

INFO: Pre-instantiating singletons in defining beans [employee]; root of factory hierarchy
Ramesh M
Embassy Golflinks Business Park Street