SpringBean的作用域(Java学习笔记)

在Spring中,bean作用域用于确定哪种类型的bean实例应该从Spring容器中返回给调用者。
目前Spring Bean的作用域或者说范围主要有五种。

作用域描述
singleton在spring IoC容器仅存在一个Bean实例,Bean以单例方式存在,bean作用域范围的默认值。
prototype每次从容器中调用Bean时,都返回一个新的实例,即每次调用getBean()时,相当于执行newXxxBean()。
request每次HTTP请求都会创建一个新的Bean,该作用域仅适用于web的Spring WebApplicationContext环境。
session同一个HTTP Session共享一个Bean,不同Session使用不同的Bean。该作用域仅适用于web的Spring WebApplicationContext环境。
application限定一个Bean的作用域为ServletContext的生命周期。该作用域仅适用于web的Spring WebApplicationContext环境。

被声明为singleton的bean

如果bean的作用域的属性被声明为singleton,那么Spring Ioc容器只会创建一个共享的bean实例。对于所有的bean请求,只要id与该bean定义的相匹配,那么Spring在每次需要时都返回同一个bean实例。

Singleton是单例类型,就是在创建起容器时就同时自动创建了一个bean的对象,不管你是否使用,他都存在了,每次获取到的对象都是同一个对象。注意,singleton作用域是Spring中的缺省作用域。
SingletonBean

package org.example;

public class SingletonBean {
    private String message;

    public void setMessage(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}

bean4.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">

    <bean id="SingletonBean" class="org.example.SingletonBean" scope="singleton"></bean>
    <!-- 或者 -->
    <!--  <bean id="SingletonBean" class="com.spring.demo.SingletonBean" ></bean> -->
</beans>

TestBean

import org.example.SingletonBean;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class TestBean {
    @Test
    public void textUser(){
//        1.获取spring文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean4.xml");
//        2.由配置文件
        SingletonBean singletonBean = (SingletonBean) context .getBean("SingletonBean");
        singletonBean.setMessage("I am object A");
        System.out.println(singletonBean.getMessage());

        SingletonBean singletonBean1 = (SingletonBean) context.getBean("SingletonBean");
        System.out.println(singletonBean1.getMessage());

    }
}

在这里插入图片描述

被声明为prototype的bean

当一个bean的作用域为prototype,表示一个bean定义对应多个对象实例。声明为prototype作用域的bean会导致在每次对该bean请求(将其注入到另一个bean中,或者以程序的方式调用容器的getBean()方法)时都会创建一个新的bean实例。prototype是原型类型,它在我们创建容器的时候并没有实例化,而是当我们获取bean的时候才会去创建一个对象,而且我们每次获取到的对象都不是同一个对象。根据经验,对有状态的bean应该使用prototype作用域,而对无状态的bean则应该使用singleton作用域。
bean5,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">
 
    <bean id="SingletonBean" class="com.spring.demo.SingletonBean" scope="prototype"></bean>
   
</beans>

ProtypeTest01类

import org.example.SingletonBean;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class PrototypeTest01 {
    @Test
    public void prototypeTest(){
        //        1.获取spring文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean5.xml");
//        2.由配置文件
        SingletonBean singletonBean = (SingletonBean) context .getBean("SingletonBean2");
        singletonBean.setMessage("I am object A");
        System.out.println(singletonBean.getMessage());

        SingletonBean singletonBean1 = (SingletonBean) context.getBean("SingletonBean2");
        System.out.println(singletonBean1.getMessage());

    }
}

运行结果
在这里插入图片描述

使用注解定义bean的作用域

除了bean.xml定义Bean的作用域之外,还可以使用注解来定义bean的作用域,
1.在bean上加注解
@Component(“SingletonBean”)注解是告诉Spring这是一个bean。
@Scope(“prototype”) 注解是告诉Spring该bean的作用域是prototype。

<context:component-scan base-package=“com.spring.demo” />就是扫描com.spring.demo包中的所有类的注解。

2.bean.xml文件修改一下。
和在bean.xml中直接定义bean和其作用域是一样的效果。其他作用域也可以使用注解方式声明bean的作用域。

request,session和application这三个作用域都是基于web的Spring WebApplicationContext实现的,只有在web环境下(比如XmlWebApplicationContext)中才能使用。
如果开发者仅仅在常规的Spring IoC容器中比如ClassPathXmlApplicationContext在中使用这些作用域,那么将会抛出一个IllegalStateException来说明使用了未知的作用域。

也就是当用户使用Spring的WebApplicationContext时,除了使用常规的singleton和prototype作用域之外,还可以使用另外3种Bean的作用域,即request,session和application。

在使用Web应用环境相关的Bean作用域时,必须在Web容器中进行一些额外的配置:

1.如果开发者使用了Spring Web MVC框架的话,每一个请求都会通过Spring的DispatcherServlet来处理,也就没有其他特殊的初始化配置,就不需要配置了。DispatcherServlet已经包含了相关的状态。

2.如果开发者使用的是低版本Web容器比如Servlet 2.5的web容器,请求不是通过Spring的DispatcherServlet(比如JSF或者Struts)来处理的。那么开发者需要注册org.springframework.web.context.request.RequestContextListener或者ServletRequestListener。
ServletContextListener只负责监听web容器启动和关闭的事件,而RequestContextListener实现了ServletRequestListener监听器接口,该监听器监听http请求事件。Web服务器接收到的每一次请求都会通知该监听器。

而在Servlet 3.0以后,这些都能够通过WebApplicationInitializer接口来实现配置。

3.如果不使用Listener,也可以考虑使用Spring的RequestContextFilter,通过http过滤器进行配置,在url-pattern中对所有的页面进行过滤。也是在web.xml中进行配置。

(4)请求作用域
请求作用域参考如下的Bean定义

Spring容器会在每次用到loginAction来处理每个HTTP请求的时候都会创建一个新的LoginAction实例。也就是说,loginActionBean的作用域是HTTP Request级别的。 当http请求调用作用域为request的bean的时候,每增加一个HTTP请求,Spring就会创建一个新的bean,在请求处理完成之后便及时销毁这个bean。开发者可以随意改变实例的状态,因为通过loginAction请求来创建的其他实例根本看不到开发者改变的实例状态,所有创建的Bean实例都是根据独立的请求来的。

(5)会话作用域
会话作用域参考如下的Bean定义

<bean id="userPreferences" class="com.foo.UserPreferences" scope="session"/>

Spring容器会在每次调用到userPreferences时,在一个单独的HTTP会话周期来创建一个新的UserPreferences实例。换言之,userPreferencesBean的作用域是HTTP Session级别的。

Session中所有http请求共享同一个请求的bean实例。Session结束后就销毁bean。 在request-scoped作用域的Bean上,开发者可以随意的更改实例的状态。同样,使用从同一个userPreferences bean定义创建的其他HTTP Session实例在看不到不是自己的内部状态的修改,因为他们是单个的HTTP会话。每个Session请求都会创建新的userPreferences实例,所以开发者更改一个Bean的状态,对于其他的Bean仍然是不可见的。

(6)全局作用域
全局作用域参考如下的Bean定义

<bean id="appPreferences" class="com.foo.AppPreferences" scope="application"/>

Spring容器会在整个web应用范围使用到appPreferences的时候创建一个新的AppPreferences的实例。也就是说,appPreferencesBean是在ServletContext级别的,作为常规的ServletContext属性。这种作用域在一些程度上来说和Spring的单例作用域相似,但是也有如下不同之处:

1.application作用域是每个ServletContext中包含一个,而不是每个SpringApplicationContext之中包含一个(某些应用中可能包含不止一个ApplicationContext)。

2.application作用域仅仅作为ServletContext的属性可见,单例Bean是ApplicationContext可见。

接下来再来简单的学习下在Spring当中如何自定义作用域:

在Spring 2.0中,Spring的Bean作用域机制是可以扩展的,这意味着,你不仅可以使用Spring提供的预定义Bean作用域,还可以定义自己的作用域,甚至重新定义现有的作用域(不提倡这么做,而且你不能覆盖内置的singleton和prototype作用域)

(7)自定义作用域
除了使用Spring已经定义好的作用域之外,还可以自定义bean的作用域。

要底线自定义作用域

1.首先需要实现自定义Scope类。

首先要先实现org.springframework.beans.factory.config.Scope这个接口,要将自定义scope集成到Spring容器当中就必须要实现这个接口。接口中有两个常用的方法,分别用于底层存储机制获取和删除这个对象。

2.在实现一个或多个自定义Scope并测试通过之后,接下来便是如何让Spring容器来识别新的作用域。registerScope方法就是在Spring容器中用来注册新的作用域。

void registerScope(String scopeName, Scope scope);

其中:第一个参数是与作用域相关的全局唯一的名称,第二个参数是准备实现的作用域的实例,就是实现Scope接口的实例。

比如实现Scope接口的类为SimpleThreadScope,要实现的自定义的bean的作用域的名称为“thread”,那就可以这么写。

Scope threadScope = new SimpleThreadScope();
beanFactory.registerScope("thread", threadScope);

3.在实现和注册自定义的scope类之后,就可以通过如下类似的Bean定义来使用自定义的Scope:

<bean id="..." class="..." scope="thread">

另外,在自定义的Scope中,开发者也不限于仅仅通过编程方式来实现自定义的bean的作用域,也可以在Spring的配置文件中配置和使用自定义作用域和,比如配置CustomScopeConfigurer实例实现自定义的作用域,声明作用域名称为“thread”,就可以在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">
 
    <bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
        <property name="scopes">
            <map>
                <entry key="thread">
                    <bean class="org.springframework.context.support.SimpleThreadScope"/>
                </entry>
            </map>
        </property>
    </bean>
 
    <bean id="bar" class="x.y.Bar" scope="thread">
        <property name="name" value="Rick"/>
        <aop:scoped-proxy/>
    </bean>
 
    <bean id="foo" class="x.y.Foo">
        <property name="bar" ref="bar"/>
    </bean>
 
</beans>

学习原文

学习原文

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值