5、Spring之bean的作用域和生命周期

来源:https://www.cnblogs.com/Javaer1995/archive/2023/08/05/17602182.html
-Advertisement-
Play Games

## 5.1、bean的作用域 ### 5.1.1、單例(預設且常用) #### 5.1.1.1、配置bean ![image](https://img2023.cnblogs.com/blog/2052479/202308/2052479-20230803010539572-840709484.p ...


5.1、bean的作用域

5.1.1、單例(預設且常用)

5.1.1.1、配置bean

image

註意:當bean不配置scope屬性時,預設是singleton(單例)

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

    <bean id="student" class="org.rain.spring.pojo.Student"></bean>

</beans>

5.1.1.2、測試

image

由控制台日誌可知,此時ioc獲取到的兩個bean本質上是同一個對象

    @Test
    public void testScope() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-scope.xml");
        Student student1 = applicationContext.getBean(Student.class);
        Student student2 = applicationContext.getBean(Student.class);
        System.out.println(student1 == student2);
    }

5.1.2、多例

5.1.2.1、配置bean

image

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

    <!--
    scope屬性:設置bean的作用域
        當屬性值為singleton時,在IOC容器中這個bean的對象始終為單實例;且創建對象的時機是IOC容器初始化時
        當屬性值為prototype時,在IOC容器中這個bean的對象有多個實例;且創建對象的時機是獲取bean時
    -->
    <bean id="student" class="org.rain.spring.pojo.Student" scope="prototype"></bean>

</beans>

5.1.2.2、測試

image

由控制台日誌可知,此時ioc獲取到的兩個bean本質上是不同的對象

5.1.3、其他作用域

如果是在WebApplicationContext環境下還會有另外兩個作用域(但不常用):

  • request:在一個請求範圍內有效

  • session:在一個會話範圍內有效

5.2、bean的生命周期

5.2.1、創建User類

image

package org.rain.spring.pojo;

/**
 * @author liaojy
 * @date 2023/8/3 - 23:59
 */
public class User {

    private Integer id;
    private String username;
    private String password;
    private Integer age;

    public User() {
        System.out.println("生命周期1:創建對象");
    }

    public User(Integer id, String username, String password, Integer age) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.age = age;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        System.out.println("生命周期2:依賴註入");
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public void initMethod(){
        System.out.println("生命周期3:初始化");
    }

    public void destroyMethod(){
        System.out.println("生命周期4:銷毀");
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                '}';
    }
}

5.2.2、配置bean

image

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

    <!--
        init-method屬性:指定初始化方法
        destroy-method屬性:指定銷毀方法
    -->
    <bean id="user" class="org.rain.spring.pojo.User" init-method="initMethod" destroy-method="destroyMethod">
        <property name="id" value="1"></property>
        <property name="username" value="張三"></property>
        <property name="password" value="123"></property>
        <property name="age" value="11"></property>
    </bean>

</beans>

5.2.3、測試

image

    @Test
    public void testLifecycle(){
        //ConfigurableApplicationContext是ApplicationContext子介面,擴展了刷新和關閉容器的方法
        ConfigurableApplicationContext ioc = new ClassPathXmlApplicationContext("spring-lifecycle.xml");
        User user = ioc.getBean(User.class);
        System.out.println(user);
        ioc.close();
    }

5.3、作用域對生命周期的影響

5.3.1、作用域為單例時

5.3.1.1、配置bean

image

    <bean id="user" class="org.rain.spring.pojo.User" init-method="initMethod" destroy-method="destroyMethod">
        <property name="id" value="1"></property>
        <property name="username" value="張三"></property>
        <property name="password" value="123"></property>
        <property name="age" value="11"></property>
    </bean>

5.3.1.2、測試

image

由控制台日誌可知,當bean的作用域為單例時,生命周期的前三個步驟會在獲取IOC容器時執行

    @Test
    public void testLifecycle(){
        //ConfigurableApplicationContext是ApplicationContext子介面,擴展了刷新和關閉容器的方法
        ConfigurableApplicationContext ioc = new ClassPathXmlApplicationContext("spring-lifecycle.xml");
    }

5.3.2、作用域為多例時

5.3.2.1、配置bean

image

    <bean id="user" class="org.rain.spring.pojo.User" init-method="initMethod" destroy-method="destroyMethod" scope="prototype">
        <property name="id" value="1"></property>
        <property name="username" value="張三"></property>
        <property name="password" value="123"></property>
        <property name="age" value="11"></property>
    </bean>

5.3.2.2、測試

image

由控制台日誌可知,當bean的作用域為多例時,生命周期的前三個步驟會在獲取bean時執行

    @Test
    public void testLifecycle(){
        //ConfigurableApplicationContext是ApplicationContext子介面,擴展了刷新和關閉容器的方法
        ConfigurableApplicationContext ioc = new ClassPathXmlApplicationContext("spring-lifecycle.xml");
        User user = ioc.getBean(User.class);
    }

5.4、bean的後置處理器

5.4.1、創建bean的後置處理器

image

註意:自定義的bean後置處理器,需要實現BeanPostProcessor介面

package org.rain.spring.process;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

/**
 * @author liaojy
 * @date 2023/8/4 - 23:52
 */
public class MyBeanProcessor implements BeanPostProcessor {
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("MyBeanProcessor-->後置處理器postProcessBeforeInitialization");
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("MyBeanProcessor-->後置處理器postProcessAfterInitialization");
        return bean;
    }
}

5.4.2、配置bean的後置處理器

image

註意:bean後置處理器不是單獨針對某一個bean生效,而是針對IOC容器中所有bean都會執行

    <!-- bean的後置處理器要放入IOC容器才能生效 -->
    <bean id="myBeanPostProcessor" class="org.rain.spring.process.MyBeanProcessor"></bean>

5.4.3、測試

image

由控制台日誌可知,bean的後置處理器會在生命周期的初始化前後添加額外的操作

    @Test
    public void testLifecycle(){
        //ConfigurableApplicationContext是ApplicationContext子介面,擴展了刷新和關閉容器的方法
        ConfigurableApplicationContext ioc = new ClassPathXmlApplicationContext("spring-lifecycle.xml");
        User user = ioc.getBean(User.class);
        System.out.println(user);
        ioc.close();
    }

5.5、具體的生命周期過程

  • bean對象創建(調用無參構造器)

  • 給bean對象設置屬性

  • bean對象初始化之前操作(由bean的後置處理器負責)

  • bean對象初始化(需在配置bean時指定初始化方法)

  • bean對象初始化之後操作(由bean的後置處理器負責)

  • bean對象就緒可以使用

  • bean對象銷毀(需在配置bean時指定銷毀方法)

  • IOC容器關閉


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 這裡給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 發現很多人還只會promise常規用法 在js項目中,promise的使用應該是必不可少的,但我發現在同事和麵試者中,很多中級或以上的前端都還停留在promiseInst.then()、promiseInst.catch()、Promis ...
  • 在JavaScript語言里有個 Math.random() 隨機函數,用於生成指定範圍內的隨機數。 #### Math.random()函數 根據官方的定義: **Math.random()** 函數返回一個浮點數, 偽隨機數在範圍[0,1),也就是說,從0(包括0)往上,但是不包括1(排除1), ...
  • 一、js有如下:1、string類型;2、number類型;3、boolean類型;4、null類型;5、undefined類型;6、Object類型;7、Array類型;8、Function類型;9、Symbol類型。共九種數據類型。js把數據類型分為“基本數據類型”和“引用數據類型”。其中6、7 ...
  • 1、父傳子( 定義:父傳子使用的是 props ) ① 首先確定父組件和子組件,然後在父組件中引入子組件,註冊並使用; 父組件代碼如下: <template> <div> <h1>父組件</h1> <!-- 使用子組件 --> <ChildView></ChildView> </div> </tem ...
  • vue3引入了Composition API,使開發者能夠更靈活組織和重用組件邏輯。採用了基於Proxy的響應式系統,對虛擬DOM進行了優化等,提升了開發體驗和性能。 ...
  • 1.查看分支 查看本地分支 git branch 查看遠程分支 git branch -r 查看本地和遠程分支 git branch -a 2.創建分支 使用以下命令創建一個本地分支 git branch <本地分支名> 使用以下命令創建一個本地分支且新建分支從特定分支拉取代碼 git branch ...
  • ## 1. scope 概念 maven 在引入依賴時,配置上有一個 scope 標簽,例如: ```xml com.mysql mysql-connector-j 8.1.0 runtime ``` 例子中的 `runtime` 表示**運行時**的依賴範圍,不同的 scope 對於項目在編譯,測 ...
  • 本節內容的概要如下; 對象已死嗎? 一、判斷對象是否存活的演算法 1、引用計數器演算法 給對象中添加一個引用計數器,每當有一個地方引用它時,計數器值就加1;當引用失效時,計數器值就減1;任何時刻計數器為0的對象就是不可能再被使用的。 客觀地說,引用計數演算法(Reference Counting)的實現簡 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...