zoukankan      html  css  js  c++  java
  • Java学习笔记-spring-Bean作用于

    零、作用域种类

    spring 中有七种作用于:

    名称 说明
    singleton 单例:Spring容器默认作用域。使用singleton定义的Bean容器中将只有一个实例。
    protoype 原型:每次通过Spring容器获取的protoype定义的Bean,容器会创建一个新的Bean实例。
    request 在同一个HTTP请求中容器会返回同一个Bean实例,对于不同的HTTP请求,则返回不同的Bean实例。每个Bean实例只在当前HTTP Request 内有效
    session 在同一个HTTP Session请求中容器会返回同一个Bean实例,对于不同的HTTP Session请求,则返回不同的Bean实例。每个Bean实例只在当前HTTP Request 内有效
    globalSession 在一个全局HTTP Session请求中容器会返回同一个Bean实例,尽在使用portlet 上下文时有效
    application 为每个ServletContext对象创建一个实例,仅在Web相关的ApplicationContext中有效
    webscoket 为每个webscoket对象创建一个实例,仅在Web相关的ApplicationContext中有效

    一、简单讲解

    Bean的作用于是通过 元素的 scope 属性来制定的,以singleton为例,示例代码如下:

    <!--beans.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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--使用singleton-->
    <bean id="scope" class="com.itheima.instance.scope.Scope" scope="singleton"/>
    </beans>
    
    
    package com.itheima.instance.scope;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class ScopeTest {
        public static void main(String[] args) {
            String xmlPath = "com/itheima/instance/scope/beans4.xml";
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
            //输出两次实例,在控制台可以看到两次的实例是一样的
            System.out.println(applicationContext.getBean("scope"));
            System.out.println(applicationContext.getBean("scope"));
        }
    }
    
    
    
  • 相关阅读:
    LeetCode 842. Split Array into Fibonacci Sequence
    LeetCode 1087. Brace Expansion
    LeetCode 1219. Path with Maximum Gold
    LeetCode 1079. Letter Tile Possibilities
    LeetCode 1049. Last Stone Weight II
    LeetCode 1046. Last Stone Weight
    LeetCode 1139. Largest 1-Bordered Square
    LeetCode 764. Largest Plus Sign
    LeetCode 1105. Filling Bookcase Shelves
    LeetCode 1027. Longest Arithmetic Sequence
  • 原文地址:https://www.cnblogs.com/gangzhucoll/p/12778214.html
Copyright © 2011-2022 走看看