Followers

springIOC: Bean Life Cycle(XML Configuration)

HelloWorld.java
===============

package myspring;

public class HelloWorld {
    private String message;
 
    public void init(){  
        System.out.println("I am Init()");
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        System.out.println("I am setter....");
        this.message = message;
    }
    public void destroy(){  
        System.out.println("I am destroy()");
    }
 
 
}

Beans.xml
==========
<?xml version="1.0" encoding="UTF-8"?>

<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="helloWorld" class="myspring.HelloWorld" init-method="init" destroy-method="destroy" >  
        <property name="message" value="Hi Hello World, how are you? " > </property>
    </bean>
</beans>

Test.java
==========
package myspring;

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

public class Test {

      public static void main(String[] args) {
          AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
          HelloWorld helloWorld = (HelloWorld)context.getBean("helloWorld");
       
          System.out.println(helloWorld.getMessage());
          context.registerShutdownHook();
         //if we comment above line it will not call destroy() method.
    }
 
}

No comments:

Post a Comment