码迷,mamicode.com
首页 > 编程语言 > 详细

Spring中bean用法(1):基本用法

时间:2015-08-27 16:50:46      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:spring

一:获取bean的方法

1.从ApplicationContex应用上下文容器中获取bean和从bean工厂容器中获取bean

具体案例:

//从ApplicationContext中取bean

ApplicationContextac=new ClassPathXmlApplicationContext("com/hsp/ioc/beans.xml");

//当我们去实例化beans.xml,该文件中配置的bean被实例(该bean scope是 singleton)从bean中取出student            

 //如果我们使用beanfactory去获取bean,当你只是实例化该容器, 那么

//容器的bean不被实例化,只有当你去使用getBean某个bean时,才会实时的创建.

 BeanFactoryfactory = new XmlBeanFactory( newClassPathResource("com/hsp/ioc/beans.xml"));

factory.getBean("student");


2.结论:

a.如果使用ApplicationContext,则配置的bean如果是 singlton不管你用不用,都被实例化.(好处就是可以预先加载,缺点就是耗内存)

b.如果是BeanFactory ,则当你获取beanfacotry时候,配置的bean不会被马上实例化,当你使用的时候,才被实例(好处节约内存,缺点就是速度)

c.规定: 一般没有特殊要求,应当使用ApplicatioContext完成(90%)


二:bean 的  scope的细节

技术分享

配置文件

<!-- 配置bean的scope生命周期 -->

<bean id="student"scope="singleton" class="com.cloud.ioc.Student">

       <propertyname="name" value="张三"/>

</bean>

 

测试代码

//获取两个student

              Students1=(Student) ac.getBean("student");

              Students2=(Student) ac.getBean("student");

              System.out.println(s1+""+s2);

 

这里singleton生命周期理解为:在配置文件中,Student类只配置一个bean,也就只对应一个对象,Student s1=(Student) ac.getBean("student");所以这种方式创建的对象是同一个。

request

session

global-session

是在web开发中才有意义.


三:种获取ApplicationContext 对象引用的方法

 

1.      ClassPathXmlApplicationContext-> 通过类路径

2.      FileSystemXmlApplicationContext-> 通过文件路径

举例:

ApplicationContext ac=newFileSystemXmlApplicationContext("文件路径beans.xml / applicationContext.xml");

3.      XmlWebApplicationContext

版权声明:博主原创文章,转载请说明出处。http://blog.csdn.net/dzy21

Spring中bean用法(1):基本用法

标签:spring

原文地址:http://blog.csdn.net/dzy21/article/details/48027519

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!