一.ClassPathXmlApplicationContext方式
從類路徑下查找spring配置文件
@Test
public void testGetBean01(){
//通過實(shí)例化ClassPathXmlApplicationContext對(duì)象完成加載spring配置文件
//這種方式在加載配置文件時(shí)就會(huì)把bean標(biāo)簽對(duì)應(yīng)的類實(shí)例化,加載到內(nèi)存中
ApplicationContext app = new ClassPathXmlApplication("applicationContext.xml");
//調(diào)用getBean方法,從容器中獲取相應(yīng)的bean
someService someService = app.getBean("someService",SomeService.class);
}
二.FileSystemApplicationContext方式
從本地文件系統(tǒng)中查找加載spring配置文件
@Test
public void testGetBean02(){
//通過實(shí)例化FileSystemApplicationContext對(duì)象完成加載spring配置文件
//這種方式在加載配置文件時(shí)就會(huì)把bean標(biāo)簽對(duì)應(yīng)的類實(shí)例化,加載到內(nèi)存中
ApplicationContext app = new ClassPathXmlApplication("applicationContext.xml");
//調(diào)用getBean方法,從容器中獲取相應(yīng)的bean
someService someService = app.getBean("someService",SomeService.class);
}
三.XmlBeanFactory方式
這種方式只是加載配置文件,只有真正調(diào)用getBean()方法的時(shí)候,才會(huì)去實(shí)例化相應(yīng)的對(duì)象,和前兩者有些不同
@Test
public void testGetBean03(){
XmlBeanFactory xbf = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
SomeService someService = (SomeService) xbf.getBean("someServiceImpl");
}
總結(jié)
1.前兩種方式
優(yōu)點(diǎn):在容器初始化的時(shí)候就會(huì)將所有對(duì)象創(chuàng)建完畢,獲取對(duì)象的效率更高
缺點(diǎn):占用內(nèi)存
2.XmlBeanFactory方式
優(yōu)點(diǎn):節(jié)省內(nèi)存
缺點(diǎn):獲取對(duì)象的效率相對(duì)來說會(huì)低