Spring--Bean的作用域

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qwl755/article/details/85726085

作用域 

  •       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"/>

运行结果:

猜你喜欢

转载自blog.csdn.net/qwl755/article/details/85726085