Friday, August 17, 2012

IOC : Initializing and destroying beans


Bean.java:
package com.lnn.ioc;

import java.util.ArrayList;
import java.util.List;

public class Bean {
      private List<String> list = null;

      public void init() {
            list = new ArrayList<String>();
            list.add("One");
            list.add("Two");
            list.add("Three");
            System.out.println("Initialized.");
      }

      public void display() {
            for (String string : list) {
                  System.out.println(string);
            }
      }

      public void destroy() {
            list = null;
            System.out.println("Destroyed.");
      }
}
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="bean"
            class="com.lnn.ioc.Bean"
            init-method="init"
            destroy-method="destroy"/>
</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);
            bean.display();
      }
}

No comments:

Post a Comment