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

Java技術(shù)棧
www.javastack.cn
關(guān)注閱讀更多優(yōu)質(zhì)文章
www.cnblogs.com/wyc1994666/p/10650480.html
本次主要想寫(xiě)spring bean的實(shí)例化相關(guān)的內(nèi)容。創(chuàng)建spring bean 實(shí)例是spring bean 生命周期的第一階段。
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">
???????
???? 