Sunday, 25 October 2015

Inject Spring inner bean using setter

Spring - Injecting Inner Beans as setter injection

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

      public Person() {
      }
     
      @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-Inner.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"/>
            <property name="address">
                  <bean class="com.rk.inner.Address">
                        <property name="area" value="dempier"/>
                        <property name="city" value="mathura"/>
                  </bean>
            </property>
      </bean>
</beans>

Use inner class as “ref” property:

<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"/>
            <property name="address" ref="addressBean"/>
      </bean>

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

importorg.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-Inner.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...