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"));
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喵叔哟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值