Friday, August 17, 2012

IOC : Autowiring by Type using annotations on setter method


Dean.java:
package com.lnn.ioc;

public class Dean {
      private String name;

      public String getName() {
            return name;
      }

      public void setName(String name) {
            this.name = name;
      }
}
Bean.java:
package com.lnn.ioc;

import org.springframework.beans.factory.annotation.Autowired;

public class Bean {
      private Dean dean = null;

      public Dean getDean() {
            return dean;
      }

      @Autowired
      public void setDean(Dean dean) {
            this.dean = dean;
      }
}
ioc.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"    
      xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.0.xsd">
      <context:annotation-config/>
      <bean id="dean" class="com.lnn.ioc.Dean">
            <property name="name" value="value"/>
      </bean>
      <bean id="bean" class="com.lnn.ioc.Bean"/>
</beans>
Test.java:
package com.lnn.ioc;

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

public class Test {
      public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("ioc.xml");
            Bean bean = context.getBean("bean", Bean.class);
            System.out.println(bean.getDean().getName());
      }
}

No comments:

Post a Comment