zoukankan      html  css  js  c++  java
  • Spring 实例化bean的初始化方法和销毁方法 initmethod destroymethod

    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调用。











  • 相关阅读:
    mysql数据类型介绍
    IO中同步、异步与阻塞、非阻塞的区别(转)
    法线
    C++配置坑-----openCv环境配置
    C++学习记录
    FBX SDK环境配置
    Unity调起外部程序cmd.exe等
    unity读写Excel表格
    Unity编辑器扩展
    Unity 读写文本 文件
  • 原文地址:https://www.cnblogs.com/yokoboy/p/3036605.html
Copyright © 2011-2022 走看看