Spring基础:快速入门spring(8):bean scope

本文深入探讨了Spring框架中Bean的作用域概念,包括默认的singleton作用域及prototype作用域,并通过示例展示了这两种作用域的不同之处。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这篇文章中我们会了解一下spring中bean scope, 并使用简单例子来看一下singleton和prototype的使用方法。

这里写图片描述

bean scope

在spring中,bean的lifecyle大体如下所示

种类详细
singleton(Default) Scopes a single bean definition to a single object instance per Spring IoC container.
prototypeScopes a single bean definition to any number of object instances.
requestScopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
sessionScopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
globalSessionScopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a Portlet context. Only valid in the context of a web-aware Spring ApplicationContext.
applicationScopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.
websocketScopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.

singleton scope

singleton也是spring的default的scope,使用这种方式的bean的scope至少有如下的特征
|特征|详细
|No.1|使用单态模式,只有一个实例

这里写图片描述

我们使用spring的reference的例子来具体说明。如上图所示,虽然在多处被使用,其实他们使用的单态方式提供的同一个实例。

修改spring设定文件

spring的default的方式,其实可以不必修改,但是为了方便,还是修改如下,将scope加入。

<?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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <context:property-placeholder location="classpath:com/liumiao/demo/spring/Person.properties" />
    <bean id="thePerson" class="com.liumiao.demo.spring.Student" init-method="initMethod" destroy-method="destroyMethod" scope="singleton">
        <property name="teachingService" ref="theService"></property>
        <property name="name" value="${person.name}" />
        <property name="country" value="${person.country}" />
    </bean>

    <bean id="theService" class="com.liumiao.demo.spring.SwimmingTeachingService">
    </bean>

</beans>

修改TestDemo

为了更清楚地确认结果,修改TestDemo,来查看使用singleton的方式下,创建的bean到底是不是同一个。

package com.liumiao.demo.spring;

import com.liumiao.demo.spring.Person;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestDemo {
    public TestDemo() {
    }

    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:com/liumiao/demo/spring/spring-cfg.xml");
        Student person = (Student) context.getBean("thePerson", Person.class);
        System.out.println(person.sayhello());
        System.out.println(person.provideTeachingService());
        System.out.println(person.getCountry());
        System.out.println(person.getName());

        Student personB = (Student)context.getBean("thePerson",Person.class);
        if (person == personB){
            System.out.println("person and personB point to the same object...");
        }else{
            System.out.println("person and personB point to the different object...");
        }
        System.out.println("person object address" + person);
        System.out.println("personB object address" + personB);

        context.close();
    }
}

执行结果

重执行结果中可以清楚地看到,person和personB实际上使用的是同一个实例。

十一月 27, 2016 10:38:31 上午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@25f38edc: startup date [Sun Nov 27 10:38:31 CST 2016]; root of context hierarchy
十一月 27, 2016 10:38:31 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [com/liumiao/demo/spring/spring-cfg.xml]
十一月 27, 2016 10:38:32 上午 org.springframework.context.support.PropertySourcesPlaceholderConfigurer loadProperties
信息: Loading properties file from class path resource [com/liumiao/demo/spring/Person.properties]
Student Default construct is called...
Student: set method: SetName:liumiao.cn
Student: set method: SetCountry:ChinaPRC
十一月 27, 2016 10:38:32 上午 org.springframework.context.support.ClassPathXmlApplicationContext doClose
User customized init-method is called
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@25f38edc: startup date [Sun Nov 27 10:38:31 CST 2016]; root of context hierarchy
Hello, I am a student.
I teach how to study...
ChinaPRC
liumiao.cn
person and personB point to the same object...
person object addresscom.liumiao.demo.spring.Student@167fdd33
personB object addresscom.liumiao.demo.spring.Student@167fdd33
User customized destroy-method is called

prototype确认

prototype方式如下,产生的是不同的实例。

这里写图片描述

修改spring的设定文件

<?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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <context:property-placeholder location="classpath:com/liumiao/demo/spring/Person.properties" />
    <bean id="thePerson" class="com.liumiao.demo.spring.Student" init-method="initMethod" destroy-method="destroyMethod" scope="prototype">
        <property name="teachingService" ref="theService"></property>
        <property name="name" value="${person.name}" />
        <property name="country" value="${person.country}" />
    </bean>

    <bean id="theService" class="com.liumiao.demo.spring.SwimmingTeachingService">
    </bean>

</beans>

执行结果

TestDemo无需再修正,可以直接确认结果如下. 可以清楚地看到使用的是不同的实例,确实和singleton的方式有所不同。

十一月 27, 2016 10:43:09 上午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@3eb07fd3: startup date [Sun Nov 27 10:43:09 CST 2016]; root of context hierarchy
十一月 27, 2016 10:43:09 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [com/liumiao/demo/spring/spring-cfg.xml]
十一月 27, 2016 10:43:09 上午 org.springframework.context.support.PropertySourcesPlaceholderConfigurer loadProperties
信息: Loading properties file from class path resource [com/liumiao/demo/spring/Person.properties]
Student Default construct is called...
Student: set method: SetName:liumiao.cn
Student: set method: SetCountry:ChinaPRC
User customized init-method is called
Hello, I am a student.
I teach how to study...
ChinaPRC
liumiao.cn
Student Default construct is called...
Student: set method: SetName:liumiao.cn
Student: set method: SetCountry:ChinaPRC
User customized init-method is called
person and personB point to the different object...
person object addresscom.liumiao.demo.spring.Student@4d95d2a2
personB object addresscom.liumiao.demo.spring.Student@53f65459
十一月 27, 2016 10:43:09 上午 org.springframework.context.support.ClassPathXmlApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@3eb07fd3: startup date [Sun Nov 27 10:43:09 CST 2016]; root of context hierarchy
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值