zoukankan      html  css  js  c++  java
  • spring对bean的管理细节

    spring对bean的管理细节

    1. 创建bean的三种方式

    1.1 方式一 使用默认构造函数创建

      在Spring的配置文件中使用bean标签, 配以id和class属性之后, 且没有其他属性和标签时

      采用的就是默认构造函数创建bean对象, 此时类中如果没有默认构造函数, 则对象无法创建

    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>

      instantiate 实例化

    1.2 方式二 使用普通工厂中的方法创建对象 (使用某个类中的方法创建对象,并存入Spring容器)

      factory-bean   factory-method
    <bean id="instanceFactory" class="com.itheima.factory.InstanceFactory"></bean>
    <bean id="accountService" factory-bean="instanceFactory" factory-method="getAccountService"></bean>

    1.3 方式三 使用工厂中的静态方法创建对象(使用某个类中的静态方法创建对象,并存入spring容器) 

    <bean id="accountService" class="com.itheima.factory.StaticFactory" factory-method="getAccountService"></bean>
    若一个类是存在于jar包中,我们无法通过修改源码的方式来提供默认构造函数,可使用方式二和三来创建对象

    2. bean对象的作用范围

      Spring默认bean对象是单例的

        Bean的作用范围调整: bean标签的scope属性

        作用: 用于指定bean的作用范围

        取值

          singleton   单例(默认值)

          prototype    多例的

          request   作用于Web应用的请求范围

          session   作用于Web应用的会话范围

          global-session   作用于集群环境的会话范围(全局会话范围),当不是集群环境时,它就是session

    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl" scope="prototype"></bean>

        

    3. bean对象的生命周期

    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"
              scope="prototype" init-method="init" destroy-method="destroy"></bean>
    init-method  bean初始化时执行的方法
    destroy-method  bean销毁时执行的方法

      单例对象:

          出生: 当然容器创建时对象出生

          活着: 只要容器还在, 对象一直活着

          死亡: 容器销毁,对象消亡

        总结: 单例对象的生命周期和容器相同

      多例对象:

          出生: 当我们使用对象时Spring为我们创建

          活着: 对象只要是在使用过程中就一直活着

          死亡: 当对象长时间不用, 且没有别的对象引用时,由JAVA的垃圾回收器回收

          

    手动关闭容器applicationcontext .close()

    调用该方法时,核心容器对象不能使用ApplicationContext 

    ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
  • 相关阅读:
    【java】浅谈java内部类
    【java】java反射初探 ——“当类也学会照镜子”
    【java】关于java类和对象,你想知道的在这里!
    【javascript】谈谈HTML5: Web-Worker、canvas、indexedDB、拖拽事件
    【Vue】Vue中的父子组件通讯以及使用sync同步父子组件数据
    【javascript】详解变量,值,类型和宿主对象
    【javascript】异步编年史,从“纯回调”到Promise
    [转] golang 字符串比较是否相等
    because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checkin
    desktoplayer.exe病毒及d:w7rtmasewcpsilmerged tu tsystem.cpp的解决方案
  • 原文地址:https://www.cnblogs.com/mkl7/p/10678514.html
Copyright © 2011-2022 走看看