您的位置:首页 > 编程语言 > Java开发

spring学习总结(五)---Spring基础知识(二:Bean的配置项及其作用域)

2016-09-05 19:43 786 查看
日期:2016-9-5

内容:主要了解Bean的配置项及其作用域的基本内容



一Bean的配置项

1、Bean比较常用的配置项:



2、Bean的作用域:

Bean的作用域有五种类型。



二、Bean作用域的实战测试:

1、Bean的singleton作用域测试:

当bean的作用域为singleton的时候,表示一个Bean容器中只存在一个一份Bean实例。

①、测试的JavaBean:

package com.spring_stydy.BeanOperation;
/**
* @author  Administrator:
* @version 创建时间:2016-9-5 下午8:01:03
* 类说明
*/
public class BeanArea {

public void testBeanArea()
{
System.out.println("测试Spring的bean作用域:"+this.hashCode());
}
}
②、applicationContext.xml配置:



这里也可以省略scope不写,因为Spring默认的作用域为singleton;

③、Test实例:

@Test
public void testBeanScope()
{
//加载Spring配置文件
ApplicationContext appc = new ClassPathXmlApplicationContext("applicationContext.xml");

BeanArea ba = (BeanArea) appc.getBean("testSpringBeanArea");

BeanArea ba2 = (BeanArea) appc.getBean("testSpringBeanArea");

//点hashCode
ba.testBeanArea();
ba2.testBeanArea();
}


④、后台打印的log:



从打印的log可知,打印的hashCode是一样的,这就是说两次请求返回的是同一个实例。

2、Bean的prototype作用月测试:

表示每一次请求都会创建新的实例。
①、这里只需要将applicationContext.xml配置文件中的scope改为prototype就可以了。



②、后台打印的log:



这次打印的log中显示,hashCode是不一样的,这说明每次请求确实创建了新实例。关于作用域的知识就阐述到这里,等在开发中有新的发现再去专研。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  singleton spring