一文了解Bean的作用域

简介: 了解Bean的作用域

概念说明

作用域

 一段程序代码中所用到的名字并不总是有效/可用的,而限定这个名字的可用性的代码范围就是这个名字的作用域。

Bean的作用域

 Bean 的作用域是指 Bean 在 Spring 整个框架中的某种行为模式。比如 singleton 单例作用域,就表示 bean 对象在整个 Spring 中只有一份,它是全局共享的,那么当其他人修改了这个值之后,那么另一个人读取到的就是被修改的值。

类型介绍

单例模式(Singleton)

唯一bean实例,由Spring容器管理其生命周期。

默认作用域,整个应用程序中只存在一个实例。

在容器启动时创建,之后共享同一个实例。

所有使用该bean的地方都会引用同一个对象。

可以通过@Scope(“singleton”)注解或者省略该注解来设置作用域为单例。

原型模式(Prototype)

每次请求都创建新的bean实例。

容器不负责管理其生命周期,每次请求都会创建一个新的实例。

每个实例都是独立的,不共享状态或数据。

可以通过@Scope(“prototype”)注解来设置作用域为原型。

请求作用域(Request)

在Web应用中有效,每次HTTP请求都会创建一个新的bean实例。

在同一个请求中,不同的组件都会使用同一个实例。

在不同的请求中,会创建不同的实例。

可以通过@Scope(“request”)注解来设置作用域为请求作用域。

会话作用域(Session)

在Web应用中有效,每个用户会话(session)期间只创建一个bean实例。

通过浏览器访问应用程序时创建一个实例,直到浏览器关闭。

不同用户的会话期间会创建不同的实例,但对于同一用户的多个请求,会使用同一个实例。

可以通过@Scope(“session”)注解来设置作用域为会话作用域。

具体应用

单例模式

1.基础服务的类

/**
 * @BelongsProject: demo
 * @BelongsPackage: com.tfjy.test
 * @Author: wuzilong
 * @Description: 单例模式实例
 * @CreateTime: 2023年2月6日08:59:35
 * @Version: 1.0
 */
@Component
public class AService {
}

2.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: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-4.0.xsd">
    <!--开启注解的支持-->
    <context:annotation-config/>
    <!-- 自动扫描指定包及其子包下的所有Bean类 -->
    <context:component-scan base-package="com.tfjy.test"/>
</beans>

3.测试类

import com.tfjy.test.AService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * @BelongsProject: demo
 * @BelongsPackage: PACKAGE_NAME
 * @Author: wuzilong
 * @Description: test
 * @CreateTime: 2023-01-28 10:01
 * @Version: 1.0
 */
public class Test {
    //bean验证
    @org.junit.Test
    public void beanTest(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        AService aServiceOne = context.getBean("AService",AService.class);
        AService aServiceTwo = context.getBean("AService",AService.class);
        System.out.println(aServiceOne);
        System.out.println(aServiceTwo);
        //通过equals方法判断两个对象是否相等
        if(aServiceOne.equals(aServiceTwo)){
            System.out.println("两次getBean方法,获得了同一个单例对象");
        }else{
            System.out.println("两次getBean方法,获得的不是同一个单例对象");
        }
    }
}

4.引入依赖的pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.example</groupId>
    <artifactId>demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.15.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
</project>

5.验证结果

271867e83b194d81841281a49ba75b77.png

 我们可以通过打印两个对象对应的hashcode码判断两个对象是否为同一个对象,我们没有设置bean对象的类型默认是单例模式。当然我们也可以通过配置将bean对象的类型改为其他类型。下面改为原型模式看看结果。

原型模式

 设置bean对象为原型模式有两个方式,第一种是通过在xml配置文件中添加配置项,另一个种是通过注解的方式设置为原型模式。

1.修改配置文件

<?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-4.0.xsd">
    <!--开启注解的支持-->
    <context:annotation-config/>
    <!-- 自动扫描指定包及其子包下的所有Bean类 -->
    <context:component-scan base-package="com.tfjy.test"/>
    <!--将AService设置为原型bean-->
    <bean id="AService" class="com.tfjy.test.AService" scope="prototype"></bean>
</beans>

46674c0c224d45a7910d039e6f57f5e8.png 通过在pom配置文件中添加对bean对象的设置,发现两个对象的hashcode码是不一致的,说明两个bean对象不是同一个对象,验证了原型模式每次请求bean对象都需要创新一个新的对象。

2.添加注解

380c4259f77a4c0d9fd774e1e89c7536.png

 通过添加 @Scope(“prototype”)也能改变bean对象的类型。

总结提升

 作用域是Spring框架中用于定义Bean的生命周期和可见性的一种机制。Spring提供了多种作用域来满足不同的需求。通过合理选择和配置Bean的作用域,我们可以控制Bean的生命周期和可见性,以满足不同的需求。这有助于提高应用程序的性能、可维护性和可扩展性。


相关文章
|
JSON 前端开发 Java
SpringBoot:SpringMVC(上)
SpringBoot:SpringMVC(上)
169 3
|
JSON 数据格式
SpringMVC-接收请求中的json数据及日期类型参数传递
SpringMVC-接收请求中的json数据及日期类型参数传递
422 0
|
6月前
|
设计模式 Java Apache
【设计模式】【创建型模式】建造者模式(Builder)
一、入门 什么是建造者模式? 建造者模式(Builder Pattern)是一种创建型设计模式,用于逐步构建复杂对象。 它通过将对象的构建过程与表示分离,使得相同的构建过程可以创建不同的表示。 为什么
234 14
|
Dubbo 应用服务中间件
错误:找不到或无法加载主类 org.apache.zookeeper.server.quorum.QuorumPeerMain
本文主要讲解如何解决Zookeeper启动时出现错误:找不到或无法加载主类 org.apache.zookeeper.server.quorum.QuorumPeerMain 的解决方案
2882 0
错误:找不到或无法加载主类 org.apache.zookeeper.server.quorum.QuorumPeerMain
|
Java
如何将OffsetDateTime转换为字符串格式的日期
【10月更文挑战第30天】如何将OffsetDateTime转换为字符串格式的日期
329 0
|
7月前
|
存储 安全 Java
Spring Security 入门与详解
Spring Security 是 Spring 框架中的核心安全模块,提供认证、授权及防护功能。本文详解其核心概念,包括认证(Authentication)、授权(Authorization)和过滤器链(Security Filter Chain)。同时,通过代码示例介绍基本配置,如 PasswordEncoder、UserDetailsService 和自定义登录页面等。最后总结常见问题与解决方法,助你快速掌握 Spring Security 的使用与优化。
1720 0
|
消息中间件 Kafka 数据库
微服务架构中,如何确保服务之间的数据一致性
微服务架构中,如何确保服务之间的数据一致性
|
存储 NoSQL MongoDB
MongoDB实战面试指南:常见问题一网打尽
MongoDB实战面试指南:常见问题一网打尽
|
开发框架 移动开发 前端开发
【Uniapp 专栏】Uniapp 与 React Native 的对比分析
【5月更文挑战第14天】Uniapp和React Native是热门的跨平台移动开发框架。Uniapp以其一套代码多端运行、丰富的组件生态和较低的学习曲线受到青睐,适合快速开发简单应用。React Native基于React,拥有活跃社区和优秀性能,适合复杂应用。React Native在性能上略胜一筹,尤其在需要接近原生体验的场景。Uniapp的官方组件弥补了社区资源不足。选择时需考虑开发效率、性能需求、团队技术栈和社区支持。
3022 1
【Uniapp 专栏】Uniapp 与 React Native 的对比分析