Spring 實例化bean的初始化方法和銷毀方法 init-method destroy-method


 

Spring版本 2.5 

首先我們應該知道:

一、spring Bean的作用域:scope=singleton(默認,單例,生成一個實例)

二、spring Bean的作用域:scope=prototype(多線程, 生成多個實例)

三、單例模式,默認在程序初始化的時候實例化(lazy-init="false")

四、prototype,getBean的時候才是實例化

五、lazy-init 只對單例模式起作用,對 prototype 不起作用(因為  prototype 默認就不是程序初始化的時候實例化的

 

1. 情況一:

    <bean id="personService6" class="com.yokoboy.service.impl.PersonServiceBean"  init-method="init" destroy-method="destory" />
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
 PersonService singleton1 = (PersonService) ctx.getBean("personService6");
 PersonService singleton2 = (PersonService) ctx.getBean("personService6");
 System.out.println(singleton1==singleton2);
ctx.registerShutdownHook();
輸出情況:

    我被實例化了
    初始化

    true
    開閉打開的資源

說明: 1. 這個bean 是單例的,

   2. 這個bean不是懶加載



2. 情況二

<bean id="personService6" class="com.yokoboy.service.impl.PersonServiceBean"   init-method="init" destroy-method="destory" scope="prototype" />
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        PersonService singleton1 = (PersonService) ctx.getBean("personService6");
        PersonService singleton2 = (PersonService) ctx.getBean("personService6");
        System.out.println(singleton1==singleton2);
        ctx.registerShutdownHook();
 
        

輸出情況:

  我被實例化了
  初始化
  我被實例化了
  初始化
  false

說明:
destroy-method="destory"只有在單例模式下再有作用。
情況三:
<bean id="personService6" class="com.yokoboy.service.impl.PersonServiceBean"   init-method="init" destroy-method="destory" />
 
        
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");

輸出:

  我被實例化了
  初始化


說明:
  程序並不知道什么時候調用
destory 方法。


最重要的是:
  在CS應用程序中,
destroy-method="destory" 這個配置基本上沒有作用,因為 摧毀方法是由容器調用的,在CS應用程序中,只有程序員自己調用。
再有,當scope是prototype的時候,對象的生存周期 Spring就不管了。只有在tomcat或者容器關閉的時候,由tomcat調用。












免責聲明!

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



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