本文主要介绍spring中ApplicationContext类实例化的3种方式和bean获取的2种方式
首先,获取ApplicationContext类的对象的3种方式:
1.通过类路径
ApplicationContext ac=new ClassPathXmlApplicationContext("decoupling/beans.xml");
FileSystemXmlApplicationContext ac=new FileSystemXmlApplicationContext("D:\\workspace\\myspring\\src\\decoupling\\beans.xml");
3.通过web路径
XmlWebApplicationContext(通过web容器获取ApplicationContext对象)
然后,获取bean的2种方法.
1.通过ApplicationContext获取
ApplicationContext ac=new ClassPathXmlApplicationContext("decoupling/beans.xml");
ChangeLetterInterface changeLetter =(ChangeLetterInterface) ac.getBean("changeLetter");
此方法采用比较多,当bean的scope值为singleton(默认值)时,在加载bean.xml文件时就已经将bean实例化了,缺点是耗内存
2.通过BeanFactory获取
BeanFactory factory=new XmlBeanFactory(new ClassPathResource("decoupling/beans.xml"));
factory.getBean("changeLetter");