国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Spring | Bean 作用域和生命周期

這篇具有很好參考價值的文章主要介紹了Spring | Bean 作用域和生命周期。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

一、通過一個案例來看 Bean 作用域的問題

Spring 是用來讀取和存儲 Bean,因此在 Spring 中 Bean 是最核心的操作資源,所以接下來我們深入學(xué)習(xí)?下 Bean 對象

假設(shè)現(xiàn)在有?個公共的 Bean,提供給 A 用戶和 B 用戶使用,然而在使用的途中 A 用戶卻 “悄悄” 地修改了公共 Bean 的數(shù)據(jù),導(dǎo)致 B 用戶在使用時發(fā)生了預(yù)期之外的邏輯錯誤

我們預(yù)期的結(jié)果是,公共 Bean 可以在各自的類中被修改,但不能影響到其他類

1、被修改的 Bean 案例

——公共 Bean:

@Component
public class Users {
	@Bean
	public User user1() {
		User user = new User();
		user.setId(1);
		user.setName("Java"); // 【重點:名稱是 Java】
		return user;
	}
}

——A 用戶使用時,進(jìn)行了修改操作:

@Controller
public class BeanScopesController {
	@Autowired
	private User user1;

    public User getUser1() {
		User user = user1;
		System.out.println("Bean 原 Name:" + user.getName());
		user.setName("悟空"); // 【重點:進(jìn)行了修改操作】
		return user;
	}
}

——B 用戶再去使用公共 Bean 的時候:

@Controller
public class BeanScopesController2 {
	@Autowired
	private User user1;

    public User getUser1() {
		User user = user1;
		return user;
	}
}

——打印 A 用戶和 B 用戶公共 Bean 的值:

public class BeanScopesTest {
	public static void main(String[] args) {
		ApplicationContext context = new 
            ClassPathXmlApplicationContext("spring-config.xml");
		
        BeanScopesController beanScopesController = context.getBean(BeanScopesController.class);
		System.out.println("A 對象修改之后 Name:" + 
                           beanScopesController.getUser1().toString());
		
        BeanScopesController2 beanScopesController2 = context.getBean(BeanScopesController2.class);
		System.out.println("B 對象讀取到的 Name:" + 
                           beanScopesController2.getUser1().toString());
	}
}

——執(zhí)行結(jié)果如下:

Bean 原 Name: Java (原來的值)
A 對象修改之后 Name: 1:悟空 (被 A 對象修改)
B 對象讀取到的 Name: 1:悟空 (B 對象中也跟著被更新了)


2、原因分析

操作以上問題的原因是因為 Bean 默認(rèn)情況下是單例狀態(tài)(singleton),也就是所有?的使用的都是同?個對象,之前我們學(xué)單例模式的時候都知道,使用單例可以很?程度上提高性能,所以在 Spring 中Bean 的作用域默認(rèn)也是 singleton 單例模式


二、作用域定義 Scope

限定程序中變量的可用范圍叫做作用域,或者說在源代碼中定義變量的某個區(qū)域就叫做作用域

而 Bean 的作用域是指 Bean 在 Spring 整個框架中的某種行為模式,?如 singleton 單例作用域,就表示 Bean 在整個 Spring 中只有?份,它是全局共享的,那么當(dāng)其他?修改了這個值之后,那么另?個?讀取到的就是被修改的值


1、Bean 的 6 種作用域

Spring 容器在初始化?個 Bean 的實例時,同時會指定該實例的作用域。Spring有 6 種作用域,最后四種是基于 Spring MVC 生效的:

  1. singleton :單例作用域(默認(rèn))

  2. prototype :原型作用域(多例作用域)

  3. request :請求作用域(Spring MVC)

  4. session :回話作用域(Spring MVC)

  5. application :全局作用域(Spring MVC)

  6. websocket :HTTP WebSocket 作用域(Spring WebSocket)

注意后 4 種狀態(tài)是 Spring MVC 中的值,在普通的 Spring 項目中只有前兩種


2、設(shè)置 bean 作用域

@scope 標(biāo)簽既可以修飾方法,也可以修飾類,有兩種設(shè)置方式:

  • 直接設(shè)置值:@Scope("prototype")
  • 類似枚舉常量的設(shè)置:@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)

2.1、測試 Bean 默認(rèn)是那種作用域

——UserBeans:

@Component
public class UserBeans {
    @Bean(name = "user1")
    public User getUser1() {
        User user = new User();
        user.setId(1);
        user.setName("zhangsan");
        return user;
    }

    @Bean(name = "user2")
    public User getUser2() {
        User user = new User();
        user.setId(2);
        user.setName("lisi");
        return user;
    }

    @Bean(name = "user3")
    public User getUser3() {
        User user = new User();
        user.setId(3);
        user.setName("Java");
        return user;
    }
}

——創(chuàng)建類 BeanScope1:

@Component
public class BeanScope1 {
    @Autowired // 注入 user3
    private User user3;

    public User getUser3() {
        User user = user3;
        user.setName("八戒");
        return user;
    }
}

——創(chuàng)建類 BeanScope2:

@Component
public class BeanScope2 {
    @Autowired
    private User user3;

    public User getUser3() {
        return user3;
    }
}

——測試:

public class App {
    public static void main(String[] args) {
        ApplicationContext context = new
                ClassPathXmlApplicationContext("spring-config.xml");
        BeanScope1 beanScope1 = context.getBean(BeanScope1.class);
        User user1 = beanScope1.getUser3();
        System.out.println("BeanScope1" + user1);

        BeanScope2 beanScope2 = context.getBean(BeanScope2.class);
        User user2 = beanScope2.getUser3();
        System.out.println("BeanScope2" + user2);
    }
}

運行結(jié)果: 說明默認(rèn)為單例

BeanScope1User{id=3, name=‘八戒’}
BeanScope2User{id=3, name=‘八戒’}


2.2、設(shè)置作用域

  • @Scope(“prototype”)
@Bean(name = "user3")
@Scope("prototype") // 原型模式,每次請求生成一個對象
public User getUser3() {
    User user = new User();
    user.setId(3);
    user.setName("Java");
    return user;
}

運行結(jié)果:

BeanScope1User{id=3, name=‘八戒’}
BeanScope2User{id=3, name=‘Java’}

  • @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    @Bean(name = "user3")
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public User getUser3() {
        User user = new User();
        user.setId(3);
        user.setName("Java");
        return user;
    }

Spring | Bean 作用域和生命周期,Java,spring,java,后端,javaee,bean

運行結(jié)果:

BeanScope1User{id=3, name=‘八戒’}
BeanScope2User{id=3, name=‘Java’}


2.3、singleton

官方說明:(Default) Scopes a single bean definition to a single object instance for each
Spring IoC container.
描述:該作?域下的Bean在IoC容器中只存在?個實例:獲取Bean(即通過
applicationContext.getBean等方法獲取)及裝配Bean(即通過@Autowired注?)都是同?
個對象。
場景:通常無狀態(tài)的Bean使?該作?域。無狀態(tài)表示Bean對象的屬性狀態(tài)不需要更新
備注:Spring默認(rèn)選擇該作?域


2.4、prototype

官方說明:Scopes a single bean definition to any number of object instances.
描述:每次對該作?域下的Bean的請求都會創(chuàng)建新的實例:獲取Bean(即通過
applicationContext.getBean等方法獲取)及裝配Bean(即通過@Autowired注?)都是新的
對象實例。
場景:通常有狀態(tài)的Bean使?該作?域


2.5、request

官方說明:Scopes a single bean definition to the lifecycle of a single HTTP request. That
is, each HTTP request has its own instance of a bean created off the back of a single
bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
描述:每次http請求會創(chuàng)建新的Bean實例,類似于prototype
場景:?次http的請求和響應(yīng)的共享Bean
備注:限定SpringMVC中使?


2.6、session

官方說明:Scopes a single bean definition to the lifecycle of an HTTP Session. Only
valid in the context of a web-aware Spring ApplicationContext.
描述:在?個http session中,定義?個Bean實例
場景:?戶回話的共享Bean, ?如:記錄?個?戶的登陸信息
備注:限定SpringMVC中使?


2.7、application(了解)

官方說明:Scopes a single bean definition to the lifecycle of a ServletContext. Only valid
in the context of a web-aware Spring ApplicationContext.
描述:在?個http servlet Context中,定義?個Bean實例
場景:Web應(yīng)?的上下?信息,?如:記錄?個應(yīng)?的共享信息
備注:限定SpringMVC中使?


2.8、websocket(了解)

官方說明:Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in
the context of a web-aware Spring ApplicationContext.
描述:在?個HTTP WebSocket的生命周期中,定義?個Bean實例
場景:WebSocket的每次會話中,保存了?個Map結(jié)構(gòu)的頭信息,將?來包裹客戶端消息
頭。第?次初始化后,直到WebSocket結(jié)束都是同?個Bean。
備注:限定Spring WebSocket中使?


2.9、單例作?域(singleton) 和 全局作?域(application) 的區(qū)別

項目類型不同: singleton 是 Spring Core 的作?域;application 是 Spring Web 中的作?域;
作用容器不同: singleton 作?于 IoC 的容器,而 application 作?于 Servlet 容器


3、Bean 原理分析

Bean 執(zhí)行流程(Spring 執(zhí)行流程):啟動 Spring 容器 -> 實例化 Bean(分配內(nèi)存空間,從無到有)
-> Bean 注冊到 Spring 中(存操作) -> 將 Bean 裝配到需要的類中(取操作)

Spring | Bean 作用域和生命周期,Java,spring,java,后端,javaee,bean


三、Bean 生命周期

1、5 個流程

所謂的生命周期指的是?個對象從誕生到銷毀的整個生命過程,我們把這個過程就叫做?個對象的生命周期。

Bean 的生命周期分為以下 5 大部分:

  1. 實例化 Bean(為 Bean 分配內(nèi)存空間)

  2. 設(shè)置屬性(Bean 注?和裝配)

  3. Bean 初始化

    • 實現(xiàn)了各種 Aware 通知的方法,如 BeanNameAware、BeanFactoryAware、ApplicationContextAware 的接口方法;

    • 執(zhí)行 BeanPostProcessor 初始化前置方法;

    • 執(zhí)行構(gòu)造方法,有兩種執(zhí)行方式:

    • 注解: @PostConstruct 初始化方法,依賴注?操作之后被執(zhí)行;

    • xml:執(zhí)行自己指定的 init-method 方法(如果有指定的話);<bean init-method=""></bean>

    • 如果兩個都設(shè)置了,先執(zhí)行注解,

    • 執(zhí)行 BeanPostProcessor 初始化后置方法

  4. 使? Bean

  5. 銷毀 Bean

    • 銷毀容器的各種方法,如 @PreDestroy (注解)、DisposableBean 接口方法、destroy-method (xml)

2、實例化和初始化的區(qū)別

實例化和屬性設(shè)置是 Java 級別的系統(tǒng)“事件”,其操作過程不可???預(yù)和修改;而初始化是給
開發(fā)者提供的,可以在實例化之后,類加載完成之前進(jìn)行?定義“事件”處理


3、生命流程的“故事”

Bean 的生命流程看似繁瑣,但咱們可以以生活中的場景來理解它,比如我們現(xiàn)在需要買一棟房子,那么我們的流程是這樣的:

  1. 先買房(實例化,從無到有);

  2. 裝修(設(shè)置屬性);

  3. 買家電,如洗衣機(jī)、冰箱、電視、空調(diào)等([各種]初始化);

  4. 入住(使用 Bean);

  5. 賣出去(Bean 銷毀)


4、生命周期演示

——創(chuàng)建類 BeanLifeComponent:

// @Component // 在 xml 中 使用 bean 標(biāo)簽注入了,不需要類注解
public class BeanLifeComponent implements BeanNameAware {
    @PostConstruct
    public void postConstruct() {
        System.out.println("執(zhí)? @PostConstruct()");
    }

    public void init() {
        System.out.println("執(zhí)? init-method");
    }
    
    public void use() {
        System.out.println("使用 bean");
    }
    
    @PreDestroy
    public void preDestroy() {
        System.out.println("執(zhí)? @PreDestroy");
    }

    public void setBeanName(String s) {
        System.out.println("執(zhí)?了 Aware 通知");
    }
}

——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:content="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 https://www.springframework.org/schema/context/spring-context.xsd">
    <content:component-scan base-package="com.beans"></content:component-scan>

    <bean id="beanLifeComponent" class="com.beans.BeanLifeComponent" init-method="init"></bean>

</beans>

——調(diào)?類:

public class App {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        BeanLifeComponent beanLifeComponent = 
            context.getBean("beanLifeComponent", BeanLifeComponent.class);
        beanLifeComponent.use();
        context.destroy(); // 注銷上下文對象
    }
}

運行結(jié)果:

執(zhí)行了 Aware 通知
執(zhí)行 @PostConstruct()
執(zhí)行 init-method
使用 bean
執(zhí)行 @PreDestroy


2、為什么先設(shè)置屬性再初始化

也就是 步驟 2 和 步驟 3 的順序,能不能打個顛倒?文章來源地址http://www.zghlxwxcb.cn/news/detail-621168.html

@Service
public class UserService {
    public UserService(){
        System.out.println("調(diào)? User Service 構(gòu)造?法");
    }
    public void sayHi(){
        System.out.println("User Service SayHi.");
    }
}

@Controller
public class UserController {
    @Resource
    private UserService userService;

    @PostConstruct
    public void postConstruct() {
        userService.sayHi(); // 執(zhí)行構(gòu)造方法時使用 會空指針
        System.out.println("執(zhí)? User Controller 構(gòu)造?法");
    }
}

到了這里,關(guān)于Spring | Bean 作用域和生命周期的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進(jìn)行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

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

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

    5.1.1.1、配置bean 注意:當(dāng)bean不配置scope屬性時,默認(rèn)是singleton(單例) 5.1.1.2、測試 由控制臺日志可知,此時ioc獲取到的兩個bean本質(zhì)上是同一個對象 5.1.2.1、配置bean 5.1.2.2、測試 由控制臺日志可知,此時ioc獲取到的兩個bean本質(zhì)上是不同的對象 如果是在WebApplicationContext環(huán)境下

    2024年02月14日
    瀏覽(24)
  • Spring系列4 -- Bean的作用域和生命周期

    Spring系列4 -- Bean的作用域和生命周期

    目錄 1. 案例 2. 作用域定義 2.1 Bean的6種作用域 2.2 設(shè)置作用域 3. Sring的執(zhí)行流程 4. Bean的生命周期 思考: 為什么不是先進(jìn)行初始化然后再進(jìn)行設(shè)置屬性呢? ????????假設(shè)現(xiàn)在有?個公共的 Bean,提供給 A ?戶和 B ?戶使?,然?在使?的途中 A ?戶卻“悄悄”地修改了公共

    2024年02月15日
    瀏覽(24)
  • 【Spring學(xué)習(xí)】Bean對象的作用域和生命周期,了解了這些你就真正熟悉spring框架了.

    【Spring學(xué)習(xí)】Bean對象的作用域和生命周期,了解了這些你就真正熟悉spring框架了.

    前言: 大家好,我是 良辰丫 ,我們已經(jīng)學(xué)會了Spring的存取,今天我們將一起來學(xué)習(xí)Bean對象的作用域和生命周期.?????? ??個人主頁:良辰針不戳 ??所屬專欄:javaEE進(jìn)階篇之框架學(xué)習(xí) ??勵志語句:生活也許會讓我們遍體鱗傷,但最終這些傷口會成為我們一輩子的財富。 ??期

    2024年02月07日
    瀏覽(26)
  • @Autowired和@Resource注解之間的關(guān)系區(qū)別,Bean的作用域和生命周期,Spring的執(zhí)行流程

    @Autowired和@Resource注解之間的關(guān)系區(qū)別,Bean的作用域和生命周期,Spring的執(zhí)行流程

    目錄 一. @Autowired 和 @Resource 注解 二. Bean的作用域? 1.?singleton(單例模式) 2.?prototype(原型模式)(多例模式) 3. 請求作用域:request 4. 會話作用域:session 三. Spring 的執(zhí)行流程 四. Bean 的生命周期? ?1. 實例化 ?2. 設(shè)置屬性? 3. Bean 初始化?? ? ?3.1 執(zhí)行各種各種 Aware 通知;? ? ?

    2024年02月04日
    瀏覽(24)
  • Bean作用域和生命周期

    Bean作用域和生命周期

    hi,今天為大家?guī)Ю睟ean的作用域和生命周期的相關(guān)知識 Bean的作用域和我們之前學(xué)過的不一樣,我們之前學(xué)的作用域是一個范圍,而現(xiàn)在指的是 Bean在Spring框架中的某種行為模式,也就是一個動作. 這樣干巴巴的說看我可能無法理解,我們來舉個例子 創(chuàng)建一個公共類的一個公共對象

    2024年02月15日
    瀏覽(33)
  • Bean 作用域和生命周期

    Bean 作用域和生命周期

    Spring 容器是用來存儲和讀取 Bean 的 , 因此 Bean 是 Spring 中最核心的操作資源. 編寫代碼過程中 , bean 對象如果有多個屬性 , 創(chuàng)建 Getter , Setter, 構(gòu)造方法 等方法 , 會產(chǎn)生大量冗長的代碼. 那么為了使代碼更加簡潔 , 我們可以使用 Lombok 框架 , 只需要一行注釋 , 就可以避免大量冗長

    2024年02月05日
    瀏覽(50)
  • Bean的作用域和生命周期

    Bean的作用域和生命周期

    目錄 1.作?域定義 1.1Bean的6個作用域 1.singleton:單例作用域 2.prototype:多例作用域 3.request:請求作用域 4.session:會話作用域 5.application:全局作用域 6.websocket:HTTP WebSocket作用域 單例作?域(singleton) VS 全局作?域(application) 1.2設(shè)置作用域 1.直接設(shè)置值@Scope(\\\"potptype\\\") 2.用枚舉設(shè)置:@Scop

    2024年02月02日
    瀏覽(25)
  • 【JavaEE進(jìn)階】Bean 作用域和生命周期

    【JavaEE進(jìn)階】Bean 作用域和生命周期

    注意在此例子中需要用到lombok lombok是什么? Lombok 是一個 Java 庫,它通過注解的方式來簡化 Java 代碼的編寫。它提供了一組注解,讓我們可以通過在代碼中添加這些注解來自動生成樣板式的代碼,如 getter、setter、構(gòu)造函數(shù)、toString 等。 使用 Lombok 可以有效地減少冗余的樣板代

    2024年02月12日
    瀏覽(25)
  • 【Spring】Bean的作用域與生命周期詳情:請簡述Spring的執(zhí)行流程并分析Bean的生命周期?

    【Spring】Bean的作用域與生命周期詳情:請簡述Spring的執(zhí)行流程并分析Bean的生命周期?

    ?我們都知道,Spring框架為開發(fā)人員提供了很多便捷,這使得開發(fā)人員能夠更加專注于應(yīng)用程序的核心業(yè)務(wù)邏輯,而不需要花費大量時間和精力在技術(shù)細(xì)節(jié)上。作為一個包含眾多工具方法的IoC容器,存取JavaBean是其極為重要的一個環(huán)節(jié)。本文就對Spring中的Bean的作用域和生命周

    2024年02月12日
    瀏覽(27)
  • Spring Bean作用域與生命周期

    Spring Bean作用域與生命周期

    目錄 Bean的作用域: Bean有六大行為模式 1、singleton:單例模式(默認(rèn)) 2、prototype: 原型模式(多例模式) 3、request: 請求作用域(Spring MVC) 4、session: 會話作用域(Spring MVC) 5、application: 全局作用域(Spring MVC) 6、websocket: HTTP WebSocket 作用域(Spring WebSocket) applicationContext和singleton的區(qū)別? Bea

    2024年02月02日
    瀏覽(25)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包