美文网首页
spring5 (4)- bean的作用域

spring5 (4)- bean的作用域

作者: 小白201808 | 来源:发表于2018-09-18 18:44 被阅读4次

一.bean的作用域

  在Spring容器中实指创建的bean对象相对其他对象的请求可见范围
  <bean id ="" class ="" scope ="">
  
  singleton:单例 在Spring Ioc容器中仅存在一个bean实例(默认的scope)
  
  prototype:多例,每次从容器中调用bean时,都会返回一个新的实例,即每次都会调用getBean()时,相对于执行new XxxBean():不会在容器启动创建对象
  
  request:用于web开发,将bean放入request范围,request.setAttribute("xxx"),在同一个request获取同一个Bean
  
  session:用于web开发,将Bean放入Session范围,在同一个Session获取同一个bean
  
  globalSeesion:一般用于prolet应用环境,分布式系统存在全局seesion概念(单击登陆),如果不是prolet环境globlesession相当于seesion。
  
  Spring 5开始出现:websocket application
  
  具体可查看文档spring-framework-5.0.0.RELEASE/docs/spring-framework-reference/core.html#beans-factory-scopes
  
  据说在开发中主要使用:scope = "singleton" ,scope = "prototype"
  对于struts1的action使用request,Struct2的Action使用prototype类型,其他使用singleton.

代码演示

(1)Dog类

 package com.keen.scope;

public class Dog {
    public Dog() {
        System.out.println(" A wangwang Dog!!!");
    }

}    

(2)DogTest-context.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<--scope默认是scope = "singleton"-->
<bean id = "dog" class ="com.keen.scope.Dog" scope = "singleton"/>
</beans>

(3)测试类

@SpringJUnitConfig
public class DogTest {
    @Autowired
    private Dog dog;
    @Autowired
    private Dog dog1;
    
    @Test
    void testName() throws Exception {
        System.out.println(dog);
        System.out.println(dog1);
    }

}

output:

 A wangwang Dog!!!
 com.keen.scope.Dog@26794848
 com.keen.scope.Dog@26794848

(4)当我们修改scope=”prototype“之后,即如一下代码

<bean id = "dog" class ="com.keen.scope.Dog" scope = "prototype"/>   

output:

A wangwang Dog!!!
com.keen.scope.Dog@26794848
com.keen.scope.Dog@302552ec  

相关文章

网友评论

      本文标题:spring5 (4)- bean的作用域

      本文链接:https://www.haomeiwen.com/subject/chsmnftx.html