zoukankan      html  css  js  c++  java
  • spring bean的生命周期

    bean 的生命周期有三种实现的方式

    第一种

    是在bean中作如下配置 并且在HelloServiceIml 中添加init和destroy方法

    <bean id="helloService" class="com.meng.test.HelloServiceIml" init-method="init" destroy-method="destroy" ></bean>

    注意:如果HelloServiceIml中没有init和destroy方法则会报错

    public class HelloServiceIml implements HelloService {
    public void init() {
    System.out.println(" init.....");

    }
    public void destroy() {
    System.out.println("destroy.....");
    }

    }

    第二种是让HelloServiceIml实现InitializingBean,DisposableBean这两个接口 并且实现里边的方法 afterPropertiesSet() destroy() 此时

    <bean id="helloService" class="com.meng.test.HelloServiceIml" ></bean>别配nit-method="" destroy-method="" 

    public class HelloServiceIml implements HelloService,InitializingBean,DisposableBean {
    public void sayHello() {
    System.out.println("hello world");
    }

    //这个是InitializingBean中接口方法的实现
    public void afterPropertiesSet() throws Exception {
    System.out.println("init........");

    }

    //这个是DisposableBean 中接口方法的实现
    public void destroy() throws Exception {
    System.out.println("destroy........");
    }

    }

    第三种是在<beans>中进行default-init-method="init" default-destroy-method="destroy" 配置 这种和第一种很相似 只不过是这种是批量的 就是该xml下的bean

    中的类如果有init和destroy方法 就都会执行 没有就不会执行 不匹配 也不会报错 就是一个可选的选项

    <beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"

    default-init-method="init" default-destroy-method="destroy">

    总结:如果有第一种存在时就会覆盖第三种 也就是说当第一种存在时第三种就不会执行 尽管匹配也不会执行 第二种不与其他两种发生冲突

    ---------------------------------------------------------------------------------------------------------

    自己总结的 有不太懂的 就看看吧 有不对的地方请大家指出 便不甚感激 

  • 相关阅读:
    Java实现找出数组中重复次数最多的元素以及个数
    java经典小算法
    java将数组中的零放到末尾
    BP神经网络
    Centos配置Caffe详解
    JAVA面试题之实现字符串的倒序输出
    Android 发送短信与接收短信
    java 选择排序法
    java数组获取最值
    spring kafka consumer原理解析二
  • 原文地址:https://www.cnblogs.com/mengfanyao/p/4491998.html
Copyright © 2011-2022 走看看