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"));
        }
    }
    
    
    
  • 相关阅读:
    Django
    MySql、Mongodb和Redis的区别
    数据库读写分离之配置Django实现数据库读写分离
    MySQL数据库优化
    01--web框架本质 wsgiref模块介绍
    CI上传图片 The filetype you are attempting to upload is not allowed.
    微信小程序 swiper和video的autoplay设置冲突问题
    关于手机端页面使用border-radius:50%不能使用div变为圆形问题
    微信小程序支付获取params的时候使用JsApiPay失败
    小程序使用笔记
  • 原文地址:https://www.cnblogs.com/gangzhucoll/p/12778214.html
Copyright © 2011-2022 走看看