长生的梦呓


  • 归档
  • 算法
  • 基础
  • 关于

  • 分类
  • 日志
  • Servlet
  • Archive
  • 数据结构
  • IO 流

  • 标签
  • 友链
  • MyBatis
  • About
  • Spring 5
  • Java SE
  • Java EE
  • Algorithms
  • 新特性
  • 位运算技巧

  • 搜索
内网穿透 项目实战 数据库 MySQL 安卓踩坑 开发工具 设计模式 Enum 枚举 Linux MyBatis-plus JSON IDEA Transactions AOP IO 流 DP IoC 与 DI 位运算技巧 工具类 学习技巧 Git JDK 排序 Spring Boot Spring MVC Spring Framework MyBatis Log4J Regex Jsoup JDBC 数据结构 递推 递归 算法 Servlet与JSP 小难 中等 简单

【Spring】(3.2)bean对象的作用域

发表于 2020-04-05 | 1 | 阅读次数 298

一、作用域

Spring中bean有6种作用域(singleton、prototype、request、session、application、websocket),该篇文章仅讲前两种。

项目结构:

在这里插入图片描述

两个实体类

public class Customer {
}
public class User {
}

pojos.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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 默认创建bean对象就是单例的(默认这一句就是加上的:scope="singleton") -->
    <bean id="user" class="com.shengjava.pojo.User" scope="singleton"></bean>

    <!-- 修改为prototype,此时每次创建的对象都是一个新对象 -->
    <bean id="customer" class="com.shengjava.pojo.Customer" scope="prototype"></bean>

</beans>

测试:

public class UserTest {
    @Test
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("pojos.xml");

        User user1 = context.getBean("user", User.class);
        User user2 = context.getBean("user", User.class);
        Customer customer1 = context.getBean("customer", Customer.class);
        Customer customer2 = context.getBean("customer", Customer.class);
        System.out.println(user1 == user2);
        System.out.println(customer1 == customer2);
    }
}

输出:

因为user1和user2作用域都是singleton单例的,他俩是一个对象,所以输出true。

而customer1和customer2作用域为prototype,每次获取都是以恶个新对象,并不相等,所以输出false。

true
false

参考官方文档:
1.5. Bean Scopes

  • 本文作者: 长生的梦呓
  • 本文链接: https://shengjava.com/archives/spring32bean对象的作用域
  • 版权声明: 本博客所有文章除特别声明外,均采用CC BY-NC-SA 3.0 许可协议。转载请注明出处!
# 内网穿透 # 项目实战 # 数据库 # MySQL # 安卓踩坑 # 开发工具 # 设计模式 # Enum # 枚举 # Linux # MyBatis-plus # JSON # IDEA # Transactions # AOP # IO 流 # DP # IoC 与 DI # 位运算技巧 # 工具类 # 学习技巧 # Git # JDK # 排序 # Spring Boot # Spring MVC # Spring Framework # MyBatis # Log4J # Regex # Jsoup # JDBC # 数据结构 # 递推 # 递归 # 算法 # Servlet与JSP # 小难 # 中等 # 简单
【Spring】(3.1)实例化bean对象(三种方式)
【Spring】(3.3)依赖注入(基于构造器)
  • 文章目录
  • 站点概览
长生的梦呓

长生的梦呓

110 日志
39 分类
40 标签
RSS
E-mail CSDN
Creative Commons
Links
  • CSDN 地址
  • waltz26
  • Ryan Wang's Blog
  • JohnNiang's Blog
  • 廖雪峰
  • 菜鸟教程
© 2021 长生的梦呓
浙ICP备20005262号-1