Share on Google+Share on Google+

Spring Inner bean example, Inner Bean in spring framework

Advertisement
In this tutorial you will learn about the inner bean in spring framework.

Inner Bean in spring framework

In the Spring framework an inner bean definition does not required to defined id or name of bean. The reason behind this is that the container ignores these values. Inner bean is used when a bean is used for one particular property. When </bean> element is defined inside the <property/> or <constructor-arg/> it is known as inner bean.

InnerBean.java

package innerbean.example;

public class InnerBean {

  private String name;
  private String address;
  
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getAddress() {
    return address;
  }
  public void setAddress(String address) {
    this.address = address;
  }
   
  @Override
  public String toString() {
    return "Inner [address=" + address + ", name=" + name + "]";
  }  
}

OuterBean.java

package innerbean.example;

public class OuterBean {
  private InnerBean inner;
  
  public OuterBean(InnerBean inner){
    this.inner=inner;
  }
  public void setInner(InnerBean inner){
    this.inner=inner;
  }
  @Override
  public String toString() {
    return "OuterBean [InnerBean=" + inner + "]";
  }
}

InnerBeanMain.java

package innerbean.example;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.
ClassPathXmlApplicationContext;


public class InnerBeanMain {
  public static void main(String[] args) {
    BeanFactory beanfactory
 = 
new ClassPathXmlApplicationContext("context.xml");
    OuterBean bean = (OuterBeanbeanfactory.getBean("outer");
    System.out.println(bean);
  }
}

context.xml

<!-- Inner Bean Example  -->

<bean id="outer" class="innerbean.example.OuterBean">
  <constructor-arg>
    <bean class="innerbean.example.InnerBean">
      <property name="name" value="satya" />
      <property name="address" value="patna" />
    </bean>
  </constructor-arg>
</bean>

<!-- End -->

When you run this application it will display output as shown below:


OuterBean [InnerBean=Inner [address=patna, name=satya]]

Download this example code

Advertisements

Advertisement

Posted on: August 12, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.