1 回答

TA貢獻(xiàn)41條經(jīng)驗(yàn) 獲得超26個贊
Spring的IOC就是一個容器,也可以稱為一個Bean工廠,專用用來生成Bean的實(shí)例。你可以簡單將IOC理解為一個Map<String, Object>,其中存放了實(shí)例化了的對象,我們可以通過指定的key獲取對應(yīng)的實(shí)例對象。簡單說下Spring IOC的執(zhí)行流程(基于xml格式):
假如有這樣一個配置文件為:applicationContext.xml
<beans>
????<bean id="person" class="com.imooc.Person">
???????? <property name="addr" ref="address"></property>
???? </bean>
???? <bean id="address" class="com.imooc.Address"></bean>
</beans>
1、讀取配置文件:applicationContext.xml(默認(rèn)的文件名稱就是這個)
2、實(shí)例化對象。根據(jù)讀取到的配置文件信息,利用反射生成“com.imooc.Person”,“com.imooc.Address”這兩個類的實(shí)例Person與Address,,并存放到Map中,key為id的屬性值,即:map.put("person",Person), map.put("address",Address)。
3、注入屬性值。找到Person對象中的屬性addr,獲取該屬性的set方法,反射調(diào)用該方法,參數(shù)為以address為key的對應(yīng)的value:即map.get("address"),method.invoke(Person, map.get("address"));
獲取Bean的方式一般是這樣:
//?ClassPathXmlApplicationContext就是一個工廠接口的一個實(shí)現(xiàn)類
ApplicationContext ?ac = new ClassPathXmlApplicationContext("applicationContext.xml");
Person person = ac.getBean("person"); // 這里的"person"就是xml中的id的屬性值
System.out.println(person.getAddr());?
要是有興趣,最好的辦法的當(dāng)然是自己去實(shí)現(xiàn)一個簡單springIOC容器(包括xml方式和Annotation方式)。這樣你就會理解的更透徹。。
添加回答
舉報