Java学习笔记-spring-Bean作用于

时间:2022-07-24
本文章向大家介绍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"));
    }
}