Spring中Bean的生命周期以及Bean的單例與多例模式

一. Bean的生命周期

bean的生命周期可以表達為:bean的定義?bean的初始化?bean的使用?bean的銷毀
在這里插入圖片描述

Bean的初始化過程

1)通過XML、Java annotation(注解)以及Java Configuration(配置類)
等方式加載Bean

2)BeanDefinitionReader:解析Bean的定義。在Spring容器啟動過程中,
會將Bean解析成Spring內部的BeanDefinition結構;
理解為:將spring.xml中的標簽轉換成BeanDefinition結構
有點類似于XML解析

3)BeanDefinition:包含了很多屬性和方法。例如:id、class(類名)、
scope、ref(依賴的bean)等等。其實就是將bean(例如)的定義信息
存儲到這個對應BeanDefinition相應的屬性中;將所有的bean標簽解析得到一個BeanDefinition定義對象,最終得到一個集合

4)BeanFactoryPostProcessor:是Spring容器功能的擴展接口。也就是在實例化之前給bean做一個拓展

注意:
1)BeanFactoryPostProcessor在spring容器加載完BeanDefinition之后,
在bean實例化之前執行的
2)對bean元數據(BeanDefinition)進行加工處理,也就是BeanDefinition
屬性填充、修改等操作

5)BeanFactory:bean工廠。它按照我們的要求生產我們需要的各種各樣的bean。BeanFactory會去解析處理整個集合,將所配置的所有JavaBean進行反射實例化

6)Aware感知接口:在實際開發中,經常需要用到Spring容器本身的功能資源
例如:BeanNameAware、ApplicationContextAware等等
BeanDefinition 實現了 BeanNameAware、ApplicationContextAware

7)BeanPostProcessor:后置處理器。在Bean對象實例化和引入注入完畢后,
在顯示調用初始化方法的前后添加自定義的邏輯。(類似于AOP的環繞通知)

二. Bean的單例與多例模式

在Spring中,bean可以被定義為兩種模式:prototype(多例)和singleton(單例)
singleton(單例):只有一個共享的實例存在,所有對這個bean的請求都會返回這個唯一的實例。單例的優點在于可以節約內存,弊端在于會有變量污染。
prototype(多例):對這個bean的每次請求都會創建一個新的bean實例,類似于new。多例的優劣則與單例相反,不會有變量污染,但卻非常消耗內存。

Spring bean默認是單例模式。

單例模式

代碼示例:

package com.xissl.beanLife;import java.util.List;public class ParamAction {private int age;private String name;private List<String> hobby;private int num = 1;public ParamAction() {super();}public ParamAction(int age, String name, List<String> hobby) {super();this.age = age;this.name = name;this.hobby = hobby;}public void execute() {System.out.println("this.num=" + this.num++);System.out.println(this.name);System.out.println(this.age);System.out.println(this.hobby);}
}

測試

package com.xissl.beanLife;import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;/** spring	bean的生命週期* spring	bean的單例多例*/
public class Demo2 {// 體現單例與多例的區別@Testpublic void test1() {ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-context.xml");
//		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-context.xml");ParamAction p1 = (ParamAction) applicationContext.getBean("paramAction");ParamAction p2 = (ParamAction) applicationContext.getBean("paramAction");// System.out.println(p1==p2);p1.execute();p2.execute();//		單例時,容器銷毀instanceFactory對象也銷毀;多例時,容器銷毀對象不一定銷毀;applicationContext.close();}}

spring配置文件

<?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的生命周期--><bean id="paramAction" class="com.xissl.beanLife.ParamAction"><constructor-arg name="name" value="三豐"></constructor-arg><constructor-arg name="age" value="21"></constructor-arg><constructor-arg name="hobby"><list><value>抽煙</value><value>燙頭</value><value>大保健</value></list></constructor-arg></bean></beans>

運行結果:
在這里插入圖片描述

這里的num值分別為1和2,則說明是單例的,單例模式即存在變量污染

在單例模式中,JavaBean是跟著spring上下文初始化的:

package com.xissl.beanLife;public class InstanceFactory {public void init() {System.out.println("初始化方法");}public void destroy() {System.out.println("銷毀方法");}public void service() {System.out.println("業務方法");}
}

測試

package com.xissl.beanLife;import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;/** spring	bean的生命週期* spring	bean的單例多例*/
public class Demo2 {// 體現單例與多例的初始化的時間點 instanceFactory@Testpublic void test2() {ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-context.xml");}}

spring配置上下文:

<bean id="instanceFactory" class="com.xissl.beanLife.InstanceFactory"scope="singleton" init-method="init" destroy-method="destroy"></bean>

運行結果:

在這里插入圖片描述

調用了初始化方法

多例模式

將spring配置文件中指定scope為prototype

<bean id="paramAction" class="com.xissl.beanLife.ParamAction" scope="prototype"><constructor-arg name="name" value="三豐"></constructor-arg><constructor-arg name="age" value="21"></constructor-arg><constructor-arg name="hobby"><list><value>抽煙</value><value>燙頭</value><value>大保健</value></list></constructor-arg></bean><bean id="instanceFactory" class="com.xissl.beanLife.InstanceFactory"scope="prototype" init-method="init" destroy-method="destroy"></bean>

運行結果:
在這里插入圖片描述

在多例模式中,JavaBean是使用的時候才會創建,銷毀跟著jvm走:

運行結果:
在這里插入圖片描述

沒有調用初始化方法

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/43157.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/43157.shtml
英文地址,請注明出處:http://en.pswp.cn/news/43157.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

2023+HuggingGPT: Solving AI Tasks with ChatGPT and itsFriends in Hugging Face

摘要&#xff1a; 語言是llm(例如ChatGPT)連接眾多AI模型(例如hugs Face)的接口&#xff0c;用于解決復雜的AI任務。在這個概念中&#xff0c;llms作為一個控制器&#xff0c;管理和組織專家模型的合作。LLM首先根據用戶請求規劃任務列表&#xff0c;然后為每個任務分配專家模…

Unity 鼠標實現對物體的移動、縮放、旋轉

文章目錄 1. 代碼2. 測試場景 1. 代碼 using UnityEngine;public class ObjectManipulation : MonoBehaviour {// 縮放比例限制public float MinScale 0.2f;public float MaxScale 3.0f;// 縮放速率private float scaleRate 1f;// 新尺寸private float newScale;// 射線pri…

【Windows系統編程】03.遠線程注入ShellCode

shellcode&#xff1a;本質上也是一段普通的代碼&#xff0c;只不過特殊的編程手法&#xff0c;可以在任意環境下&#xff0c;不依賴于原有的依賴庫執行。 遠程線程 #include <iostream> #include <windows.h> #include <TlHelp32.h>int main(){HANDLE hPr…

Educational Codeforces Round 153 (Rated for Div. 2)ABC

Educational Codeforces Round 153 (Rated for Div. 2) 目錄 A. Not a Substring題目大意思路核心代碼 B. Fancy Coins題目大意思想核心代碼 C. Game on Permutation題目大意思想核心代碼 A. Not a Substring 題目大意 給定一個只包含“&#xff08;”和“&#xff09;”這兩…

react-native-webview RN和html雙向通信

rn登錄后得到的token需要傳遞給網頁&#xff0c;js獲取到的瀏覽器信息需要傳遞給rn RN Index.js: import React from react import { WebView } from react-native-webview import useList from ./useListexport default function Index(props) {const { uri, jsCode, webVie…

iPhone刪除的照片能恢復嗎?不小心誤刪了照片怎么找回?

iPhone最近刪除清空了照片還能恢復嗎&#xff1f;大家都知道&#xff0c;照片對于我們來說是承載著美好回憶的一種形式。它記錄著我們的平淡生活&#xff0c;也留住了我們的美好瞬間&#xff0c;具有極其重要的紀念價值。 照片不小心誤刪是一件非常難受的事&#xff0c;那么iP…

android TextView 超出長度使用省略號

在Android中最常見的需求&#xff0c;就是在在外部展示信息時&#xff0c;需要簡要展示內容。TextView僅需在靜態布局文件中設置以下幾個屬性&#xff1a; android:maxWidth“100dp” // 寬度是多少才算超出 android:maxLines"2" // 高度多少才算超出 android:elli…

React下載文件的兩種方式

React下載文件的兩種方式 - 代碼先鋒網 不知道有用沒用看著挺整齊 沒試過 1、GET類型下載 download url > {const eleLink document.createElement(a);eleLink.style.display none;// eleLink.target "_blank"eleLink.href url;// eleLink.href record;d…

Centos7 配置Docker鏡像加速器

docker實戰(一):centos7 yum安裝docker docker實戰(二):基礎命令篇 docker實戰(三):docker網絡模式(超詳細) docker實戰(四):docker架構原理 docker實戰(五):docker鏡像及倉庫配置 docker實戰(六):docker 網絡及數據卷設置 docker實戰(七):docker 性質及版本選擇 認知升…

CentOS系統環境搭建(五)——Centos7安裝maven

centos系統環境搭建專欄&#x1f517;點擊跳轉 Centos7安裝maven 下載壓縮包 maven下載官網 解壓 壓縮包放置到/usr/local tar -xvf apache-maven-3.9.2-bin.tar.gz配置環境變量 vim /etc/profile在最下面追加 MAVEN_HOME/usr/local/apache-maven-3.9.2 export PATH${MAV…

Jenkins 監控dist.zip文件內容發生變化 觸發自動部署

為Jenkins添加plugin http://xx:xx/manage 創建一個任務 構建觸發器 每3分鐘掃描一次&#xff0c;發現指定文件build.zip文件的MD5發生變化后 觸發任務

【C++學習手札】一文帶你認識C++虛繼承??

食用指南&#xff1a;本文在有C基礎的情況下食用更佳 &#x1f340;本文前置知識&#xff1a;C虛函數&#xff08;很重要&#xff0c;內部剖析&#xff09; ??今日夜電波&#xff1a;僕らのつづき—柊優花 1:06 ━━━━━━?&#x1f49f;──────── 3:51 …

創建密碼庫/創建用戶帳戶/更新 Ansible 庫的密鑰/ 配置cron作業

目錄 創建密碼庫 創建用戶帳戶 更新 Ansible 庫的密鑰 配置cron作業 創建密碼庫 按照下方所述&#xff0c;創建一個 Ansible 庫來存儲用戶密碼&#xff1a; 庫名稱為 /home/curtis/ansible/locker.yml 庫中含有兩個變量&#xff0c;名稱如下&#xff1a; pw_developer&#…

神經網絡基礎-神經網絡補充概念-39-梯度消失與梯度爆炸

簡介 梯度消失和梯度爆炸是在深度神經網絡中訓練過程中可能出現的問題&#xff0c;導致模型難以訓練或無法收斂。這些問題與反向傳播算法中的梯度計算有關。 概念 梯度消失&#xff08;Gradient Vanishing&#xff09;&#xff1a;在深層神經網絡中&#xff0c;特別是具有很…

File inclusion

文章目錄 File inclusion(local)File inclusion(remote) File inclusion(local) 隨便選擇一個點擊提交&#xff0c;提交后觀察 url ?filename 我們可以使用相對路徑../../../../../訪問我們想要看到的文件內容 查看windows系統的主機映射文件../../../../Windows/System32/…

ShardingSphere 可觀測 SQL 指標監控

ShardingSphere并不負責如何采集、存儲以及展示應用性能監控的相關數據&#xff0c;而是將SQL解析與SQL執行這兩塊數據分片的最核心的相關信息發送至應用性能監控系統&#xff0c;并交由其處理。 換句話說&#xff0c;ShardingSphere僅負責產生具有價值的數據&#xff0c;并通過…

Go 語言中排序的 3 種方法

原文鏈接&#xff1a; Go 語言中排序的 3 種方法 在寫代碼過程中&#xff0c;排序是經常會遇到的需求&#xff0c;本文會介紹三種常用的方法。 廢話不多說&#xff0c;下面正文開始。 使用標準庫 根據場景直接使用標準庫中的方法&#xff0c;比如&#xff1a; sort.Intsso…

【C++】AVL樹(平衡二叉樹)

目錄 一、AVL樹的定義二、AVL樹的作用三、AVL樹的插入操作插入——平衡因子的更新插入——左單旋插入——右單旋插入——左右雙旋插入——右左雙旋 四、ALVL樹的驗證五、AVL樹的性能 一、AVL樹的定義 AVL樹&#xff0c;全稱 平衡二叉搜索&#xff08;排序&#xff09;樹。 二…

一次Linux圖形化界面恢復

一次Linux 圖形化界面恢復 一次Linux 圖形化界面恢復出現問題場景問題排查 一次Linux 圖形化界面恢復 出現問題場景 使用xmanager遠程連接虛機的CentOS7系統圖形界面出現已拒絕x11轉移申請問題&#xff0c;在折騰X11過程中&#xff0c;安裝與卸載的過程中不小心把xorg-x11-xa…

HCIP的交換機實驗

題目 拓撲圖 PC1/3接口用access 創建WLAN LSW1 創建WLAN [lsw1]vlan batch 2 to 6[lsw1-Ethernet0/0/1]p [lsw1-Ethernet0/0/1]port l [lsw1-Ethernet0/0/1]port link- [lsw1-Ethernet0/0/1]port link-flap [lsw1-Ethernet0/0/1]port link-type acc [lsw1-Ethernet0/0…