spring中建立bean物件時多例和單例的區別
阿新 • • 發佈:2019-01-09
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="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-2.5.xsd"> <!-- init-method * 該方法是由spring容器執行 * 在建構函式之後執行 * 如果在建構函式之後,在呼叫方法之前要做一些工作,可以在init方法中完成 destroy-method * 如果該bean是單例(預設就是singlton),則在spring容器關閉或者銷燬的時候,執行該方法 * 如果該bean是多例(scope="prototype"),則spring容器不負責銷燬 說明:要想讓spring容器控制bean的生命週期,那麼該bean必須是單例 如果該bean是多例,該bean中還有資源,關閉資源的操作由程式設計師完成 --> <bean id="helloWorld" class="cn.edu.initdestroy.HelloWorld" scope="prototype" init-method="init" destroy- method="destroy"></bean> </beans>
注意: 當一個bean是多例模式的情況下,lazy-init為false或者default無效。
<!-- 在預設情況下,spring建立bean是單例模式 scope singleton 預設 單例 屬性是共享的 一般情況下,把資料存放在方法中的變數中 prototype 多例 當一個bean是多例模式的情況下,lazy-init為false或者default無效 --> <bean id="helloWorld" class="cn.itcast.spring0909.scope.HelloWorld" scope="prototype" lazy-init="false"></bean>
<!-- 在啟動spring容器的時候,spring容器配置檔案中的類就已經建立完成物件了 lazy-init default 即為 false true 在context.getBean的時候才要建立物件 * 優點 如果該bean中有大資料存在,則什麼時候context.getBean,什麼時候建立物件 可以防止資料過早的停留在記憶體中,做到了懶載入 * 缺點 如果spring配置檔案中,該bean的配置有錯誤,那麼在tomcat容器啟動的時候,發現不了 false 在啟動spring容器的時候建立物件 * 優點 如果在啟動tomcat時要啟動spring容器, 那麼如果spring容器會錯誤,這個時候tomcat容器不會正常啟動 * 缺點 如果存在大量的資料,會過早的停留在記憶體中 --> <bean id="helloWorld" class="cn.edu.spring0909.createobject.when.HelloWorl" lazy-init="true"></bean> <bean id="person" class="cn.edu.spring0909.createobject.when.Person" lazy-init="true"></bean>