日期: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是不一样的,这说明每次请求确实创建了新实例。关于作用域的知识就阐述到这里,等在开发中有新的发现再去专研。