Spring bean scope

Spring有如下5个 bean  范围:

1:singleton—每次从spring container 中返回一个单例对象,不进行新对象的创建;

2:prototype—和singleton相反,每次从spring container中返回不同的对象,每次进行新对象的创建

3:request—返回一个single bean 对象 每次 HTTP  request
4:session—返回一个single bean 对象 每次 HTTP  session
5:globalSession—返回一个single bean 实例每次 全局 HTTP session


定义一个类:
package com.myapp.core.beanscope;

public class PersonService {
   private String  message;

	public String getMessage() {
		return message;
	}
	
	public void setMessage(String message) {
		this.message = message;
	}
   
}

定义对应的xml配置文件:
   
   <!-- bean scope test about  singleton  and  prototype -->
   <!-- change  the scope  in the  singleton  and  prototype -->
   
   <bean id="personService" class="com.myapp.core.beanscope.PersonService" scope="prototype">
   
   </bean>
编写测试类:MainTest.java
package com.myapp.core.beanscope;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainTest {
  public static void main(String[] args) {
	  
	ApplicationContext  context =new  ClassPathXmlApplicationContext("SpringBeans.xml");
	
	PersonService  person = (PersonService)context.getBean("personService");
	
	person.setMessage("hello  spring");
	
	PersonService  person_new = (PersonService)context.getBean("personService");
	
	System.out.println(person.getMessage());
	System.out.println(person_new.getMessage());
	
	//explain   output  the same  message  validate  the  singleton  scope  only create  a instance;
	
	// when  scope is singleton output following:
	/**
	 * hello spring
	 * hello spring
	 */
	
	
	//the  following  test  need  to  modify  personServie bean's scope  to  prototype  then  see the output
	
	//when  scope is prototype output as following;
	
	/**
	 * hello  spring
	 * null
	 */
	
}
} 

当把xml中配置文件的   scope="singleton"的时候;
输出
hello spring
hello spring
证明每次从spring container中获取的是一个 对象


把xml配置文件中改为如下  scope="prototype"的时候

输出:
hello spring
null
证明每次从spring container中获取的是不同的对象,每次都创建新对象。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值