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">

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

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

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

  • 相关阅读:
    【机器学习】:Xgboost和GBDT的不同与比较
    golang pprof
    终于解决了AMD RYZEN 3970X的散热问题
    2022,你好
    二叉树的遍历 → 不用递归,还能遍历吗
    异或运算的巧用 → 不用额外的变量,如何交换两个变量的值?
    关于 RocketMQ 事务消息的正确打开方式 → 你学废了吗
    单向链表的花式玩法 → 还在玩反转?
    二叉树的简单实战 → 一起温故下二叉树的遍历
    序列化和反序列化
  • 原文地址:https://www.cnblogs.com/mengfanyao/p/4491998.html
Copyright © 2011-2022 走看看