1.從ApplicationContext中取bean
ApplicationContext ac = new ClassPathXmlApplicationContext("/com/bean.xml");
當(dāng)我們實(shí)例化bean.xml時(shí),該文件中配置的bean都會(huì)被實(shí)例化。(該bean scope是singleton)
2.從BeanFactory中取bean
BeanFactory factory= new XmlBeanFactory(new ClassPathResource("/com/bean.xml"));
factory.getBean("student");//取bean的時(shí)候才會(huì)實(shí)例化
當(dāng)使用beanfactory去獲取bean于微,當(dāng)你只是實(shí)例化該容器,那么容器內(nèi)的bean不會(huì)被實(shí)例化询微,只有當(dāng)使用某個(gè)bean(getBean)時(shí),才會(huì)實(shí)時(shí)去實(shí)例化該bean狂巢。
總結(jié)
1.如果使用ApplicationContext撑毛,則配置的bean如果是singleton不管你用還是不用,都被實(shí)例化唧领。好處是可以預(yù)先加載藻雌,壞處是浪費(fèi)內(nèi)存。
2.BeanFactory疹吃,當(dāng)使用BeanFactory實(shí)例化對象時(shí)蹦疑,配置的bean不會(huì)馬上被實(shí)例化。當(dāng)你使用該bean時(shí)才會(huì)被實(shí)例化(getBean)萨驶。好處是節(jié)約內(nèi)存歉摧,缺點(diǎn)是速度比較慢。多用于移動(dòng)設(shè)備的開發(fā)上。
3.一般沒有特殊要求叁温,應(yīng)當(dāng)使用ApplicationContext完成再悼。
三種獲取ApplicationContext對象引用的方法
1.ClassPathXmlApplicationContext 通過類路徑。
2.FileSystemXmlApplicationContext 通過文件路徑膝但。
ApplicationContext ac = FileSystemXmlApplicationContext("d:\\com\\bean.xml");
3.XmlWebApplicationContext:從web系統(tǒng)中加載冲九。
注:本文截取網(wǎng)絡(luò)(http://blog.sina.com.cn/s/blog_5f8ac4b70101jmkc.html),如有侵權(quán)跟束,請通知莺奸,本人立即刪除。