Nearby lessons

7 of 35

Spring - Nested Beans

📌 What You Will Learn
  • Understand Spring - Nested Beans
  • See working code examples
  • Learn from common mistakes and Q&A

Learn Spring - Nested Beans step by step — simple explanations, complete programs with their output, common beginner mistakes, and exam-style MCQs.

Nested Beans

Declaring a bean configuration in another bean configuration is called as Inner Beans or

Nested Beans.

IN Bean class, if we declare any property of User defined class type then we have to use

<bean> tag for the user defined class as value to the respective property under

<property> tag.

<beans>

<bean .... >

<property name="variable of USer defined class type">

<bean id="--" class="---"/>

</property>

</bean>

</beans>

EX:

Account.java

package com.durgasoft.beans;

public class Account {

private String accNo;

private String accName;

private String accType;

private long balance;

setXXX()

getXXX()

}

Employee.java

package com.durgasoft.beans;

public class Employee {

private String eid;

private String ename;

private float esal;

private String eaddr;

private Account acc;

setXXX()

getXXX()

public void displayEmpDetails(){

System.out.println("Employee Details");

System.out.println("-----------------------");

System.out.println("Employee Id :"+eid);

System.out.println("Employee Name :"+ename);

System.out.println("Employee Salary :"+esal);

System.out.println("Employee Address:"+eaddr);

System.out.println();

System.out.println("Account Details");

System.out.println("---------------------");

System.out.println("Account Number :"+acc.getAccNo());

System.out.println("Account Name :"+acc.getAccName());

System.out.println("Account Type :"+acc.getAccType());

System.out.println("Account Balance :"+acc.getBalance());

}

}

applicationContext.xml

<beans>

<bean id="emp" class="com.durgasoft.beans.Employee">

<property name="eid" value="E-111"/>

<property name="ename" value="Durga"/>

<property name="esal" value="10000"/>

<property name="eaddr" value="Hyd"/>

<property name="acc">

<bean id="account" class="com.durgasoft.beans.Account">

<property name="accNo" value="abc123"/>

<property name="accName" value="Durga"/>

<property name="accType" value="Savings"/>

<property name="balance" value="20000"/>

</bean>

</property>

</bean>

</beans>

Test.java

package com.durgasoft.test;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.durgasoft.beans.Employee;

public class Test {

public static void main(String[] args)throws Exception {

ApplicationContext context=new

ClassPathXmlApplicationContext("applicationContext.xml");

Employee emp=(Employee)context.getBean("emp");

emp.displayEmpDetails();

}

}

📝 Key Takeaways
  • Key ideas of Spring - Nested Beans explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end