自己做的demo:鏈接: https://pan.baidu.com/s/1GrNT7tL2E2MrWHOw7-jamA 提取碼: jvbk
![watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2ppa3VpY3VpNzQwMg_size_16_color_FFFFFF_t_70][]
Bean的延長加載
在某些情況下,我們可能希望把bean的創(chuàng)建延遲到使用階段,以免消耗不必要的內(nèi)存,Spring也非常自愿地支持了延遲bean的初始化。因此可以在配置文件中定義bean的延遲加載,這樣Spring容器將會(huì)延遲bean的創(chuàng)建直到真正需要時(shí)才創(chuàng)建。通常情況下,從一個(gè)已創(chuàng)建的bean引用另外一個(gè)bean,或者顯示查找一個(gè)bean時(shí)會(huì)觸發(fā)bean的創(chuàng)建即使配置了延遲屬性,因此如果Spring容器在啟動(dòng)時(shí)創(chuàng)建了那些設(shè)為延長加載的bean實(shí)例,不必驚訝,可能那些延遲初始化的bean可能被注入到一個(gè)非延遲創(chuàng)建且作用域?yàn)閟ingleton的bean。在xml文件中使用bean的lazy-init屬性可以配置改bean是否延遲加載,如果需要配置整個(gè)xml文件的bean都延遲加載則使用defualt-lazy-init屬性,請(qǐng)注意lazy-init屬性會(huì)覆蓋defualt-lazy-init屬性。
<beans xmlns=" [http://www.springframework.org/schema/beans][http_www.springframework.org_schema_beans]"
xmlns:xsi=" [http://www.w3.org/2001/XMLSchema-instance][http_www.w3.org_2001_XMLSchema-instance]"
xmlns:context=" [http://www.springframework.org/schema/context][http_www.springframework.org_schema_context]"
xsi:schemaLocation="
[http://www.springframework.org/schema/beans][http_www.springframework.org_schema_beans] [http://www.springframework.org/schema/beans/spring-beans.xsd][http_www.springframework.org_schema_beans_spring-beans.xsd]
[http://www.springframework.org/schema/context][http_www.springframework.org_schema_context]
" default-lazy-init="true">
<bean name="accountDao" lazy-init="false"
class="com.zejian.spring.springIoc.dao.impl.AccountDaoImpl"/>
<bean name="accountService" class="com.zejian.spring.springIoc.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"/>
</bean>
</beans>
請(qǐng)務(wù)必明確一點(diǎn),默認(rèn)情況下Spring容器在啟動(dòng)階段就會(huì)創(chuàng)建bean,這個(gè)過程被稱為預(yù)先bean初始化,這樣是有好處的,可盡可能早發(fā)現(xiàn)配置錯(cuò)誤,如配置文件的出現(xiàn)錯(cuò)別字或者某些bean還沒有被定義卻被注入等。當(dāng)然如存在大量bean需要初始化,這可能引起spring容器啟動(dòng)緩慢,一些特定的bean可能只是某些場合需要而沒必要在spring容器啟動(dòng)階段就創(chuàng)建,這樣的bean可能是Mybatis的SessionFactory或者Hibernate SessionFactory等,延遲加載它們會(huì)讓Spring容器啟動(dòng)更輕松些,從而也減少?zèng)]必要的內(nèi)存消耗。
![20200715214614131.png][]
annotation-config
此屬性等同于<context:annotation-config />配置,默認(rèn)就是true,也就是說,如果配置了context:component-scan其實(shí)就沒有必要配置annotation-config 了。
本文來源于:宋文超super,專屬平臺(tái)有csdn、思否(SegmentFault)、 簡書、 開源中國(oschina),轉(zhuǎn)載請(qǐng)注明出處。