spring Inner Beans With Example

A <bean/> element inside the <property/> or <constructor-arg/> elements defines a so-called inner bean.
An inner bean definition does not require a defined id or name; if specified, the container does not use such a value as an identifier. The container also ignores the scope flag on creation: Inner beans are always anonymous and they are always created with the outer bean. It is not possible to inject inner beans into collaborating beans other than into the enclosing bean or to access them independently.
Let's See an Example For Spring Inner beans

Tools Used In This Article

  • Spring 4.3.2
  • Maven 4.0.0
  • JDK 1.7

Project Directory Structure

Maven Dependencies

Add The Following Dependencies to the pom.xml

  • spring-core
  • spring-beans
  • spring-context


<project xmlns="http://maven.apache.org/POM/4.0.0"





2.Writing Spring Beans

In This Example Im Writing TWo Spring Beans Named With Aadhar and Account


package com.practice;

public class Aadhar {
private int aadhaarNumber;

public int getAadhaarNumber() {
return aadhaarNumber;

public void setAadhaarNumber(int aadhaarNumber) {
this.aadhaarNumber = aadhaarNumber;

public String toString() {
return "Aadhar [aadhaarNumber=" + aadhaarNumber + "]";



package com.practice;

public class Account {
private int accountId;
private String name;
private Aadhar aadhaar;
public int getAccountId() {
return accountId;
public void setAccountId(int accountId) {
this.accountId = accountId;
public String getName() {
return name;
public void setName(String name) {
this.name = name;
public Aadhar getAadhaar() {
return aadhaar;
public void setAadhaar(Aadhar aadhaar) {
this.aadhaar = aadhaar;
public String toString() {
return "Account [accountId=" + accountId + ", name=" + name
+ ", aadhaar=" + aadhaar + "]";


3.Setting Up Spring Configuration File


<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
<bean id = "accountBean" class = "com.practice.Account">
<property name = "accountId" value = "11111"></property>
<property name="name" value = "xxxxx"></property>

<property name = "aadhaar" ref = "aadhaar"></property>
<bean id = "aadhaar" class = "com.practice.Aadhar">
<property name = "aadhaarNumber" value = "2222"></property>

4.Now Create Test class ,RunThe Code


package com.practice.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.practice.Account;

public class AppTest {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Account account = (Account)context.getBean("accountBean");




INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
Account [accountId=11111, name=xxxxx, aadhaar=Aadhar [aadhaarNumber=2222]]