Spring创建一个Bean 耗时
applicationContext中只有一个bean
<bean id="testUnit" lazy-init="true">
</bean>
通过以下代码,进行测试。
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"test/applicationContext.xml"},true);// bean layz-init=truelong startTime = System.currentTimeMillis();TestUnit testUnit = (TestUnit) context.getBean("testUnit", context.getType("testUnit"));System.out.println(System.currentTimeMillis()-startTime);// 使用new创建startTime = System.currentTimeMillis();testUnit = new TestUnit();System.out.println(System.currentTimeMillis()-startTime);// spring已经实例化bean,获取。startTime = System.currentTimeMillis();testUnit = context.getBean("testUnit",TestUnit.class);System.out.println(System.currentTimeMillis()-startTime);执行结果:
2010-8-4 14:09:13 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@5ffb18: startup date [Wed Aug 04 14:09:13 CST 2010]; root of context hierarchy
2010-8-4 14:09:13 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [test/applicationContext.xml]
2010-8-4 14:09:13 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1d15445: defining beans [testUnit]; root of factory hierarchy
16
0
0
以上可见,spring的beanFactory创造bean的用时,也是不少的。