Thursday, August 16, 2012

IOC : Instantiation using an instance factory method


Bean.java:
package com.lnn.ioc;

public class Bean {
      private String name;

      public String getName() {
            return name;
      }

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

public class FactoryBean {
      public Bean createBean() {
            return new Bean();
      }
}

ioc.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-3.0.xsd">
      <bean id="factory"  class="com.lnn.ioc.FactoryBean"/>
      <bean id="bean" factory-bean="factory" factory-method="createBean">
            <property name="name" value="value"/>
      </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.getName());
      }
}

No comments:

Post a Comment