創(chuàng)建Spring Bean實(shí)例化是Spring Bean生命周期的第一階段

Bean的生命周期主要有如下幾個(gè)步驟:
「詳細(xì)介紹:Spring In Action是這樣講的:」
在實(shí)例化Bean之前在BeanDefinition里頭已經(jīng)有了所有需要實(shí)例化時(shí)用到的元數(shù)據(jù),接下來(lái)Spring只需要選擇合適的實(shí)例化方法以及策略即可。
「BeanDefinition」
Spring容器啟動(dòng)的時(shí)候會(huì)定位我們的配置文件,加載文件,并解析成Bean的定義文件BeanDefinition
右邊的Map里存儲(chǔ)這bean之間的依賴關(guān)系的定義BeanDefinition,比如OrderController依賴OrderService這種
實(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í)例化方法
「使靜態(tài)工廠方法實(shí)例化」
- public class FactoryInstance {
- public FactoryInstance() {
- System.out.println("instance by FactoryInstance");
- }
- }
- public class MyBeanFactory {
- public static FactoryInstance getInstanceStatic(){
- return new FactoryInstance();
- }
- }
- 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">
- factory-method="getInstanceStatic"/>
「使用實(shí)例工廠方法實(shí)例化」
- public class MyBeanFactory {
- /**
- * 實(shí)例工廠創(chuàng)建bean實(shí)例
- *
- * @return
- */
- public FactoryInstance getInstance() {
- return new FactoryInstance();
- }
- }
- 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">
![]()
微信二維碼