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











  • 相关阅读:
    Spring Boot 结合 Redis 序列化配置的一些问题
    基于SpringBoot的代码在线运行的简单实现
    将Spring实战第5版中Spring HATEOAS部分代码迁移到Spring HATEOAS 1.0
    用Spring Security, JWT, Vue实现一个前后端分离无状态认证Demo
    使用最新AndroidStudio编写Android编程权威指南(第3版)中的代码会遇到的一些问题
    C# 内存管理优化畅想----前言
    C# 内存管理优化实践
    C# 内存管理优化畅想(三)---- 其他方法&结语
    C# 内存管理优化畅想(二)---- 巧用堆栈
    C# 内存管理优化畅想(一)---- 大对象堆(LOH)的压缩
  • 原文地址:https://www.cnblogs.com/yokoboy/p/3036605.html
Copyright © 2011-2022 走看看