spring容器中對象單例還是多例


默認Spring容器中所有bean都是單例的;
優點:可以節省空間,減少資源浪費。
缺點:可能會引發線程安全問題

如果在Bean標簽上設置scope = “prototype”,當前bean對象就是多例的,每次獲取當前類的實例,spring容器就會創建當前類的實例;
優點:不會引發線程安全問題
缺點:每次獲取實例都會創建新的實例,會占用服務器的內存空間,造成浪費

注解中,在@Controller、@Service、@Repository(或@Component)注解旁加@Scope=(scopeName=“prototype”) ,即多例,默認為單例

 

<?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>
<!-- 
          在默認情況下,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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM