1. Spring中bean的多种作用域

在默认情况下,Spring应用上下文中所有的bean都是以单例(singleton)的形式创建的,即不管给定的一个bean被注入到其他bean多少次,每次所注入的都是同一个实例。

Spring定义了多种作用域,可以基于这些作用域创建bean:

  1. 单例(Singleton):在整个应用中,只创建bean的一个实例。
  2. 原型(Prototype):每次注入或者通过Spring应用上下文获取的时候,都会创建一个新的bean实例。
  3. 会话(Session):在Web应用中,为每个会话创建一个bean实例。
  4. 请求(Request):在Web应用中,为每个请求创建一个bean实例。

单例是默认的作用域,如果要使用其它的作用域创建bean,需要使用@Scope注解,该注解可以和@Component@Service@Bean等注解一起使用。

2. 示例

为了更好的理解,我们通过具体的代码示例来理解下Singleton与ProtoType的区别。

2.1 新建Singleton类型的bean

package chapter03.scope;

import org.springframework.stereotype.Service;

@Service
public class DemoSingletonService {
}

因为Spring默认配置的Scope是Singleton,因此以上代码等价于以下代码:

package chapter03.scope;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service; @Service
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class DemoSingletonService {
}

上面的代码也可以写成@Scope("singleton")

2.2 新建ProtoType类型的bean

如果是自动装配bean,语法为:

package chapter03.scope;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service; @Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class DemoPrototypeService {
}

上面的代码也可以写成@Scope("prototype")

如果是在Java配置类中声明bean,语法为:

@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public DemoPrototypeService demoPrototypeService() {
return new DemoPrototypeService();
}

如果是在xml中声明bean,语法为:

<bean id="demoPrototypeService" class="chapter03.scope.DemoPrototypeService"
scope="prototype"/>

2.3 新建配置类

package chapter03.scope;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; @Configuration
@ComponentScan("chapter03.scope")
public class ScopeConfig {
}

2.4 测试

新建一个Main类,在main()方法中,分别从Spring容器中获取2次Bean,然后判断Bean的实例是否相等:

package chapter03.scope;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScopeConfig.class); DemoSingletonService s1 = context.getBean(DemoSingletonService.class);
DemoSingletonService s2 = context.getBean(DemoSingletonService.class); DemoPrototypeService p1 = context.getBean(DemoPrototypeService.class);
DemoPrototypeService p2 = context.getBean(DemoPrototypeService.class); System.out.println("s1 与 s2 是否相等:" + s1.equals(s2));
System.out.println("p1 与 p2 是否相等:" + p1.equals(p2)); context.close();
}
}

运行结果如下:

从运行结果也可以看出,默认情况下即Singleton类型的Bean,不管调用多少次,只会创建一个实例。

3. 注意事项

Singleton类型的Bean,@Scope注解的值必须是:singleton。

ProtoType类型的Bean,@Scope注解的值必须是:prototype。

即使是大小写不一致也不行,如我们将DemoPrototypeService类的代码修改为:

package chapter03.scope;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service; @Service
@Scope("PROTOTYPE")
public class DemoPrototypeService {
}

此时运行代码,就会报错:

4. 源码及参考

源码地址:https://github.com/zwwhnly/spring-action.git,欢迎下载。

汪云飞《Java EE开发的颠覆者:Spring Boot实战》

原创不易,如果觉得文章能学到东西的话,欢迎点个赞、评个论、关个注,这是我坚持写作的最大动力。

如果有兴趣,欢迎添加我的微信:zwwhnly,等你来聊技术、职场、工作等话题(PS:我是一名奋斗在上海的程序员)。

Spring入门(五):Spring中bean的作用域的更多相关文章

  1. spring入门(五) spring mvc+hibernate

    核心是让SessionFactory由Spring管理 1.引入依赖 <!-- https://mvnrepository.com/artifact/org.springframework/sp ...

  2. Spring入门2. IoC中装配Bean

    Spring入门2. IoC中装配Bean 20131125 前言: 上一节学习了Spring在JavaProject中的配置,通过配置文件利用BeanFactory和ApplicationConte ...

  3. 7 -- Spring的基本用法 -- 5... Spring容器中的Bean;容器中Bean的作用域;配置依赖;

    7.5 Spring容器中的Bean 7.5.1 Bean的基本定义和Bean别名 <beans.../>元素是Spring配置文件的根元素,该元素可以指定如下属性: default-la ...

  4. spring中bean的作用域属性singleton与prototype的区别

    1.singleton 当一个bean的作用域设置为singleton, 那么Spring IOC容器中只会存在一个共享的bean实例,并且所有对bean的请求,只要id与该bean定义相匹配,则只会 ...

  5. java——spring中bean的作用域

    文章:理解Spring框架中Bean的作用域 博客地址:https://baijiahao.baidu.com/s?id=1610298792072480906&wfr=spider& ...

  6. 详解Spring中Bean的作用域与生命周期

    摘要:在利用Spring进行IOC配置时,关于bean的配置和使用一直都是比较重要的一部分,同时如何合理的使用和创建bean对象,也是小伙伴们在学习和使用Spring时需要注意的部分,所以这一篇文章我 ...

  7. Spring核心技术(五)——Spring中Bean的作用域

    前文概述了Spring的容器,Bean,以及依赖的一些信息,本文将描述一下Bean的作用域 Bean的作用域 当开发者定义Bean的时候,同时也会定义了该如何创建Bean实例.这些具体创建的过程是很重 ...

  8. Spring中bean的作用域与生命周期

    在 Spring 中,那些组成应用程序的主体及由 Spring IOC 容器所管理的对象,被称之为 bean.简单地讲,bean 就是由 IOC 容器初始化.装配及管理的对象,除此之外,bean 就与 ...

  9. Spring中Bean的作用域和生命周期

    作用域的种类 Spring 容器在初始化一个 Bean 的实例时,同时会指定该实例的作用域.Spring3 为 Bean 定义了五种作用域,具体如下. 1)singleton 单例模式,使用 sing ...

随机推荐

  1. Java8 Streams 让集合操作飞起来

    前言 接上篇文章 java8 新特性 由于上篇过于庞大,使得重点不够清晰,本篇单独拿出 java8 的 Stream 重点说明 ,并做了点补充. 基本说明 Stream 是基于 java8 的 lam ...

  2. [LeetCode]Jump GameII

    题目:Jump GameII 如果要求找最小的调数,考虑扩张的思路. 思路如下: 1.首先找起始位能到达的范围是否覆盖了最终位置,并记录下搜索中的最远能到达的位置值,即max{nums[i] + i} ...

  3. jenkins自动化部署项目3 --设置用户

    我直接设置的admin ,jenkins可以新建多个用户,并赋予不同的权限(TODO) 等后续需要严格规范操作人的时候再补充

  4. Java String 类解析

    I.构造函数: public String() {} 默认构造函数 public String(String original) {} 使用原有字符串构造  public String(char va ...

  5. 记一次jmeter从txt文本获取数值并给测试计划的变量赋值,jmeter永久性修改变量。

    前言: 需要永久性的改变变量. 其实这个办法并不是最好的,但是是最容易实现的.后期可做成从数据库里直接取值. 赋值BeanShell import java.io.File; import java. ...

  6. 读《深入理解Elasticsearch》点滴-改善查询相关性

    1.标准查询 query match _all query:"搜索字符串" operator:or 2.多匹配查询+区分权重 query multi_match "que ...

  7. layui 上传图片回显并点击放大实现

    1.页面代码布局 <div class="layui-col-xs12 form-group"> <div class="layui-col-xs6&q ...

  8. 动态set mybatis与ibatis的写法

    mybatis: <set> <if test="obj.buyerId != null"> buyerId = #{obj.buyerId}, </ ...

  9. linux 指定tomcat的具体路径

    1.直接修改catalina.sh中对应的变量 CATALINA_HOME=/xx/xxCATALINA_BASE=/xx/xx (该方法需要找到所有的变量进行修改,不适合,推荐使用方式2) 2.在p ...

  10. latex转word公式 java (latextoword,latex_word,latex2word,latex_omml)

    latex_word 主要目的:     给大家分享一个我的原创作品:latex转为word公式(omml)工具 [java] 此工具主要用于将含有latex公式的文本下载成word时,将latex转 ...