Spring Bean Scope

In Spring, bean scope is used to decide which type of bean instance should be return from Spring container back to the caller.

5 types of bean scopes supported :

  1. singleton – Return a single bean instance per Spring IoC container
  2. prototype – Return a new bean instance each time when requested
  3. request – Return a single bean instance per HTTP request. *
  4. session – Return a single bean instance per HTTP session. *
  5. globalSession – Return a single bean instance per global HTTP session. *

In most cases, you may only deal with the Spring’s core scope – singleton and prototype, and the default scope is singleton.

P.S * means only valid in the context of a web-aware Spring ApplicationContext

Singleton vs Prototype

Here’s an example to show you what’s the different between bean scope : singleton and prototype.

package usoft;

public class CustomerService {
    String message;

    public String getMessage() {
        return message;
    }

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

1. Singleton example

If no bean scope is specified in bean configuration file, default to singleton.

<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-2.5.xsd">
 
       <bean id="customerService" 
            class="com.mkyong.customer.services.CustomerService" />
 
</beans>

Run it

package com.mkyong.common;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
package usoft;

public class App {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext(new String[]{"Spring-Customer.xml"});

        CustomerService custA = (CustomerService) context.getBean("customerService");
        custA.setMessage("Message by custA");
        System.out.println("Message : " + custA.getMessage());

        //retrieve it again
        CustomerService custB = (CustomerService) context.getBean("customerService");
        System.out.println("Message : " + custB.getMessage());
    }
}

Output

Message : Message by custA

Message : Message by custA

Since the bean ‘customerService’ is in singleton scope, the second retrieval by ‘custB’ will display the message set by ‘custA’ also, even it’s retrieve by a new getBean() method. In singleton, only a single instance per Spring IoC container, no matter how many time you retrieve it with getBean(), it will always return the same instance.

2. Prototype example

If you want a new ‘customerService’ bean instance, every time you call it, use prototype instead.

<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-2.5.xsd">
 
   <bean id="customerService" class="com.mkyong.customer.services.CustomerService" 
         scope="prototype"/>
 
</beans>

Run it again

Message : Message by custA

Message : null

In prototype scope, you will have a new instance for each getBean() method called.

3. Bean scopes annotation

You can also use annotation to define your bean scope.

package usoft;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Service
@Scope("prototype")
public class CustomerService {
    String message;

    public String getMessage() {
        return message;
    }

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

}

Enable auto component scanning

<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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
 
       <context:component-scan base-package="com.mkyong.customer" />
 
</beans>
时间: 2024-12-21 13:49:33

Spring Bean Scope的相关文章

Spring Bean Scope 有状态的Bean 无状态的Bean

http://blog.csdn.net/anyoneking/article/details/5182164 在Spring的Bean配置中,存在这样两种情况: [xhtml] view plaincopy <bean id="testManager" class="com.sw.TestManagerImpl" scope="singleton" /> <bean id="testManager" cla

spring Bean 配置中scope 和 lazy-init

Spring Bean配置默认为单实例 Bean默认的是单例的. 如果不想单例需要如下配置:<bean id="user" class="..." singleton="false"/> singleton就是配置这个bean是否是单例的,如果不写,就是默认值true. spring Bean 配置中 scope的作用 1.Bean的作用域可以通过Bean标签的scope属性进行设置,Bean的作用域包括:默认情况下scope=&qu

spring bean的scope

spring bean 的scope有5种: Singleton:当一个bean的作用域为singleton, 那么Spring IoC容器中只会存在一个共享的bean实例,并且所有对bean的请求,只要id与该bean定义相匹配,则只会返回bean的同一实例. 换言之,当把一个bean定义设置为singlton作用域时,Spring IoC容器只会创建该bean定义的唯一实例.这个单一实例会被存储到单例缓存(singleton cache)中,并且所有针对该bean的后续请求和引用都将返回被缓

Spring基础 快速入门spring(11) bean scope注解方式

在前面我们已经学习过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. prototype Scopes a sing

Spring学习(15)--- 基于Java类的配置Bean 之 @Bean &amp; @Scope 注解

默认@Bean是单例的,但可以使用@Scope注解来覆盖此如下: @Configuration public class MyConfiguration { @Bean @Scope("prototype") public MovieCatalog movieCatalog(){ //... } } Bean的作用域包括singleton.prototype.request.session.global session 例子:

Spring Bean

一.Spring的几大模块:Data access & Integration.Transcation.Instrumentation.Core Spring Container.Testing. 二.Spring Bean 2.1.声明Bean a.简单的bean装配方式 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework

spring singleton scope与singleton pattern的区别

单态定义:     Singleton模式主要作用是保证在Java应用程序中,一个类Class只有一个实例存在. 在很多操作中,比如建立目录 数据库连接都需要这样的单线程操作. 还有, singleton能够被状态化; 这样,多个单态类在一起就可以作为一个状态仓库一样向外提供服务,比如,你要论坛中的帖子计数器,每次浏览一次需要计数,单态类能否保持住这个计数,并且 能synchronize的安全自动加1,如果你要把这个数字永久保存到数据库,你可以在不修改单态接口的情况下方便的做到. 另外方面,Si

spring中scope作用域(转)

摘自 http://www.cnblogs.com/qq78292959/p/3716827.html 今天研究了一下scope的作用域.默认是单例模式,即scope="singleton".另外scope还有prototype.request.session.global session作用域.scope="prototype"多例.再配置bean的作用域时,它的头文件形式如下: 如何使用spring的作用域: <bean id="role&quo

Spring 中 ApplicationContext 和 BeanFactory 的区别,以及 Spring bean 作用域

//从ApplicationContext 中取 bean ApplicationContext ac = new ClassPathXmlApplicationContext ( "com/hsp/beans.xml" ) ; ac.getBean("beanId"); 当我们去实例化beans.xml,该文件中配置的 bean 就被实例化(不论你用还是不用,bean对象都在那),而且该对象是singleton单例的.(每个bean都有scope属性,可以人为的设