国产秋霞理论久久久电影-婷婷色九月综合激情丁香-欧美在线观看乱妇视频-精品国avA久久久久久久-国产乱码精品一区二区三区亚洲人-欧美熟妇一区二区三区蜜桃视频

天天用 Spring,bean 實(shí)例化原理你懂嗎?

共 1393字,需瀏覽 3分鐘

 ·

2020-07-27 19:18

Java技術(shù)棧

www.javastack.cn

關(guān)注閱讀更多優(yōu)質(zhì)文章



來(lái)源:小小木的博客

www.cnblogs.com/wyc1994666/p/10650480.html

本次主要想寫(xiě)spring bean的實(shí)例化相關(guān)的內(nèi)容。創(chuàng)建spring bean 實(shí)例是spring bean 生命周期的第一階段。

bean 的生命周期主要有如下幾個(gè)步驟:

在實(shí)例化bean之前在BeanDefinition里頭已經(jīng)有了所有需要實(shí)例化時(shí)用到的元數(shù)據(jù),接下來(lái)spring 只需要選擇合適的實(shí)例化方法以及策略即可。實(shí)例化方法有兩大類分別是工廠方法和構(gòu)造方法實(shí)例化,后者是最常見(jiàn)的。

spring默認(rèn)的實(shí)例化方法就是無(wú)參構(gòu)造函數(shù)實(shí)例化。

如我們?cè)趚ml里定義的 以及用注解標(biāo)識(shí)的bean都是通過(guò)默認(rèn)實(shí)例化方法實(shí)例化的。

  • 兩種實(shí)例化方法(構(gòu)造函數(shù) 和 工廠方法)

  • 源碼閱讀

  • 實(shí)例化策略(cglib or 反射)

兩種實(shí)例化方

使用適當(dāng)?shù)膶?shí)例化方法為指定的bean創(chuàng)建新實(shí)例:工廠方法,構(gòu)造函數(shù)實(shí)例化。

代碼演示

啟動(dòng)容器時(shí)會(huì)實(shí)例化所有注冊(cè)的bean(lazy-init懶加載的bean除外),對(duì)于所有單例非懶加載的bean來(lái)說(shuō)當(dāng)從容器里獲取bean(getBean(String name))的時(shí)候不會(huì)觸發(fā),實(shí)例化階段,而是直接從緩存獲取已準(zhǔn)備好的bean,而生成bean的時(shí)機(jī)則是下面這行代碼運(yùn)行時(shí)觸發(fā)的。

@Test
public?void?testBeanInstance(){????????
????//?啟動(dòng)容器
????ApplicationContext?context?=?new?ClassPathXmlApplicationContext("spring-beans.xml");
}

一 使用工廠方法實(shí)例化(很少用)

1.靜態(tài)工廠方法
public?class?FactoryInstance?{????
????public?FactoryInstance()?{
????????System.out.println("instance?by?FactoryInstance");
????}
}

public?class?MyBeanFactory?{????public?static?FactoryInstance?getInstanceStatic(){????????return?new?FactoryInstance();
????}
}
"1.0"?encoding="UTF-8"?>"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?http://www.springframework.org/schema/context?http://www.springframework.org/schema/context/spring-context.xsd">
?
????"factoryInstance"?class="spring.service.instance.MyBeanFactory"?factory-method="getInstanceStatic"/>


輸出結(jié)果為:

instance by FactoryInstance

2.實(shí)例工廠方法
public?class?MyBeanFactory?{????

????/**
?????*?實(shí)例工廠創(chuàng)建bean實(shí)例
?????*
?????*?@return
?????*/
????public?FactoryInstance?getInstance()?{????????return?new?FactoryInstance();
????}
}
"1.0"?encoding="UTF-8"?>
"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?http://www.springframework.org/schema/context?http://www.springframework.org/schema/context/spring-context.xsd">
???????
????