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 keytool证书工具使用小结(转)
    Https socket 代理
    SSL连接出现的问题
    Https 代理 sslsocket
    Https socket 连接
    linux系统一键安装phpstudy的lnmp环境
    Yii2框架实现计数器功能
    yii2框架增删改查案例
    yii2框架原生的结合框架使用的图片上传
    php将抓取的图片链接下载到本地
  • 原文地址:https://www.cnblogs.com/mkl7/p/10678514.html
Copyright © 2011-2022 走看看