1. 程式人生 > >Spring--Bean的作用域

Spring--Bean的作用域

作用域 

 

  •       singleton:(預設 )單例,在一個bean容器中只存在一份 
  •       prototype:每次請求(每次使用)建立新的例項,destory方式不生效 
  •       request:每次Http請求建立一個例項且僅在當前request內生效 
  •       session:同上,在session內生效 
  •       global session:基於portlet的Web中生效,如果在web,基於session
     

singleton作用域 

package cn.itcast.hello;

public class Hello {

}

base4.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
   http://www.springframework.org/schema/beans 
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop 
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
   http://www.springframework.org/schema/tx 
   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
   http://www.springframework.org/schema/context      
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">
   
   <bean id="hello" class="cn.itcast.hello.Hello" scope="singleton"/>
</beans>
package cn.itcast.hello;

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

public class HelloTest {
	@Test
	public void HelloTest(){
		String xmlpath="cn/itcast/hello/beans4.xml";
		ApplicationContext context=new ClassPathXmlApplicationContext(xmlpath);
		System.out.println(context.getBean("hello"));
		System.out.println(context.getBean("hello"));
	}
}

 執行結果:

 

prototype作用域


   <bean id="hello" class="cn.itcast.hello.Hello" scope="singleton"/>

改為:

   <bean id="hello" class="cn.itcast.hello.Hello" scope="prototype"/>

執行結果: