Sunday, 25 October 2015

Inject Spring inner bean as Constructor parameter

Spring - Injecting Inner Beans as constructor parameter

package com.rk.inner;
public class Person {
      private String name;
      private Address address;

      public Person(Address address) {
            this.address = address;

      public String toString() {
            return name +" lives at "+ address;
      // setters and getters

public class Address {
      private String area;
      private String city;

      public String toString() {
            return "area : "+area+" city: "+city;
      // setters and getters

Use inner class as property:

<beans xmlns=""

      <bean id="PersonBean" class="com.rk.inner.Person">
            <property name="name" value="rajesh" />
                  <bean class="com.rk.inner.Address">
                        <property name="area" value="dempier" />
                        <property name="city" value="mathura" />

import org.springframework.context.ApplicationContext;

public class TestInnerClass {
      public static void main( String[] args ) {
            ApplicationContext context =
            new ClassPathXmlApplicationContext(
            new String[] {"com/rk/inner/Spring-Person-Constructor.xml"});

            Person cust = (Person) context.getBean("PersonBean");

Output: rajesh lives at area : dempier city: mathura

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...