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;
      }

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

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

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

Use inner class as property:

Spring-Person-Constructor.xml
<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
      http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

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

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

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");
            System.out.println(cust);
      }
}

Output: rajesh lives at area : dempier city: mathura


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...