Spring入门笔记(二) Bean的生命周期

来源:互联网 发布:java读取word文件内容 编辑:程序博客网 时间:2024/06/06 23:30

参考慕课网Spring入门篇

  1. 定义
    在.xml文件中配置的id和class
  2. 初始化
    即生成bean的实例

    • 实现org.springframework.beans.factory.InitializingBean接口,覆盖afterPropertiesSet方法
    • 在.xml文件中配置init-method

      <bean id = "" class = "" init-method = "init"></bean>
  3. 使用
    即从bean容器中取出实例,调用相应的方法
  4. 销毁
    即在bean容器停止时,销毁bean容器中所创建的实例

    • 实现org.springframework.beans.factory.DisposaBean接口,覆盖destroy方法
    • 在.xml文件中配置destroy-method

      <bean id = "" class = "" destroy-method = "destroy"></bean>

    如果接口和配置的方法同时使用的话,会先执行接口的方法再执行配置的方法

    此外还可以配置全局默认初始化、销毁方法

    <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans.xsd"     default-init-method = "init" default-destroy-method = "destroy"></beans>

    当一个bean实现了接口或者存在配置的话,默认的初始化和销毁的方法不会生效,会被覆盖掉
    如果使用了全局默认初始化销毁方法,类文件中两个默认方法可以不存在,bean的执行过程并不会失败
    但是如果使用接口或.xml配置的方法,那么初始化和销毁方法必须存在

原创粉丝点击