Spring Framework

Spring Projects

Spring Project 1

adplus-dvertising
Example of Non-Intrusive approach
Previous Home Next

Introduction: A non-intrusive approach an initialization method is defined in the bean and is specified in the bean configuration using init-method attribute.

Technology use to run this source code

  1. Spring 2.5
  2. Eclipse
  3. JDK 1.6

Source Code:

applicationContext.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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="one" class="org.r4r.One" init-method="init"/>
<bean id="two" class="org.r4r.Two" init-method=
"init" destroy-method="cleanUp"/>
</beans>

One.java

package org.r4r;
import org.springframework.beans.factory.DisposableBean;
public class One implements DisposableBean {
@Override
public void destroy() throws Exception {
System.out.println
("One is given a chance to performed cleanup operation");
}
public One(){
System.out.println("One is instantiated...");
}
public void init(){
System.out.println("One is given a chance to initialize");
}
}

Two.java

package org.r4r;
import org.springframework.beans.factory.InitializingBean;
public class Two implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("Intrusive initialization of two");
}
public Two(){
System.out.println("Two is instantiated....");
}
public void init(){
System.out.println("Nonintrunsive initialization of two....");
}
public void cleanUp(){
System.out.println("Non-intrunsive cleanup of two...");
}
}

Test.java

package org.r4r;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory f=new XmlBeanFactory(r);
System.out.println("Obtaining bean one...");
@SuppressWarnings("unused")
One one=(One)f.getBean("one");
System.out.println("Obtaining bean two...");
@SuppressWarnings("unused")
Two two=(Two)f.getBean("two");
f.isSingleton("one");
//f.isPrototype("two");
}
}

output:

Obtaining bean one...
One is instantiated...
One is given a chance to initialize
Obtaining bean two...
Two is instantiated....
Intrusive initialization of two
Nonintrunsive initialization of two....
Previous Home Next