e2

滴滴侠,fai抖

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

本文主要介绍spring中ApplicationContext类实例化的3种方式和bean获取的2种方式

首先,获取ApplicationContext类的对象的3种方式:

1.通过类路径

ApplicationContext ac=new ClassPathXmlApplicationContext("decoupling/beans.xml");
 
 
2.通过文件路径
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");

 

此方法采用较少,主要用于移动等内存少的设备上,其延时加载,在执行factory.getBean("changeLetter")时才对bean进行实例化,
 
posted on 2017-03-15 16:50  纯黑Se丶  阅读(570)  评论(0编辑  收藏  举报