/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/
///////////////////////////////////////////////////////////////////////////////////////
//File: lookup.xml
///////////////////////////////////////////////////////////////////////////////////////
public interface DemoBean {
public MyHelper getMyHelper();
public void someOperation();
}
///////////////////////////////////////////////////////////////////////////////////////
public class MyHelper {
public void doSomethingHelpful() {
// do something!
}
}
///////////////////////////////////////////////////////////////////////////////////////
public class StandardLookupDemoBean implements DemoBean {
private MyHelper helper;
public void setMyHelper(MyHelper helper) {
this.helper = helper;
}
public MyHelper getMyHelper() {
return this.helper;
}
public void someOperation() {
helper.doSomethingHelpful();
}
}
///////////////////////////////////////////////////////////////////////////////////////
public abstract class AbstractLookupDemoBean implements DemoBean {
public abstract MyHelper getMyHelper();
public void someOperation() {
getMyHelper().doSomethingHelpful();
}
}
///////////////////////////////////////////////////////////////////////////////////////
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
public class BeanFactoryAwareLookupDemoBean implements BeanFactoryAware,
DemoBean {
private BeanFactory factory = null;
public void setBeanFactory(BeanFactory factory) throws BeansException {
this.factory = factory;
}
public MyHelper getMyHelper() {
return (MyHelper) factory.getBean("helper");
}
public void someOperation() {
getMyHelper().doSomethingHelpful();
}
}
///////////////////////////////////////////////////////////////////////////////////////
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.util.StopWatch;
public class LookupPerformance {
public static void main(String[] args) {
BeanFactory factory = new XmlBeanFactory(new FileSystemResource(
"build/lookup.xml"));
DemoBean abstractBean = (DemoBean) factory.getBean("abstractLookupBean");
DemoBean factoryBean = (DemoBean) factory.getBean("factoryLookupBean");
testPerf(abstractBean);
testPerf(factoryBean);
}
public static void testPerf(DemoBean bean) {
StopWatch stopWatch = new StopWatch();
stopWatch.start("perfTest");
for (int x = 0; x < 1000000; x++) {
MyHelper helper = bean.getMyHelper();
helper.doSomethingHelpful();
}
stopWatch.stop();
System.out.println("1000000 gets took "
+ stopWatch.getTotalTimeSeconds() + " seconds");
}
}
LookupPerformance.zip( 1,479 k)