温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring中init-method与destroy-method属性怎么用

发布时间:2021-08-26 11:51:51 来源:亿速云 阅读:270 作者:小新 栏目:开发技术

这篇文章将为大家详细讲解有关Spring中init-method与destroy-method属性怎么用,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

    Spring init-method与destroy-method属性使用

    知识点介绍:

    有时候在bean初始化之后要执行的初始化方法,以及在bean销毁时执行的方法。这时就需要配置init-method和destroy-method属性,顾名思义,配置初始与销毁的方法。

    操作步骤:

    1、创建Speaker对象

    public class Speaker { 
    	private String name;
    	private String topic;	
    	private Speaker(String name,String topic){
    		this.name = name;
    		this.topic = topic;
    	}
    	
    	/**
    	 * Speaker实例化时执行的方法
    	 */
    	private void init() {
    		System.out.println("执行Speaker 的 初始化方法 init");
    	}
     
    	/**
    	 * Speaker销毁时执行的方法
    	 */
    	private void destroy() {
    		System.out.println("执行Speaker 的销毁方法 destroy");
    	}
    	
    	public void teach() {		
    		System.out.println(toString());
    	}
    	
    	@Override
    	public String toString() {
    		return "Speaker [name=" + name + ", topic=" + topic + "]";
    	}
    }

    2、创建Spring配置文件beanLearn05.xml

    <?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">
     
     <!-- Learn 05 init-method和destroy-method属性的使用 -->
     <bean id="speaker05" class="com.mahaochen.spring.learn05.Speaker"
      init-method="init" destroy-method="destroy">
      <constructor-arg index="0" value="elle" />
      <constructor-arg index="1" value="Study Hard!" />
     </bean>
    </beans>

    3、将Spring配置文件beanLearn05.xml引入到主配置文件beans.xml中。

    <!-- Learn 04  使用实例工厂方式实例化Bean -->
     <import resource="com/mahaochen/spring/learn05/beanLearn05.xml"/>

    4、编写测试类TestSpring05.java。

    public class TestSpring05 { 
     public static void main(String[] args) {  
      ApplicationContext appContext = new ClassPathXmlApplicationContext("beans.xml");
      Speaker speaker05 = (Speaker) appContext.getBean("speaker05");
      speaker05.teach();
      ((ClassPathXmlApplicationContext) appContext).close();
     }
    }

    init-method="init"和 destroy-method="close" 作用

    一般在我们配置数据源的时候,会这样写

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">

    init-method="init" destroy-method="close" 作用:

    init-method="init"是指bean被初始化时执行的方法,当bean实例化后,执行init-method用于初始化数据库连接池。

    destroy-method="close" 是指bean被销毁时执行的方法 Spring容器关闭时调用该方法即调用close()将连接关闭。

    关于“Spring中init-method与destroy-method属性怎么用”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

    向AI问一下细节

    免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

    AI