欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

Spring init-method与destroy-method属性的用法解析

时间:2022-02-19 09:39:12|栏目:JAVA代码|点击:

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 redis 如何实现模糊查找key

栏    目:JAVA代码

下一篇:Spring整合WebSocket应用示例(上)

本文标题:Spring init-method与destroy-method属性的用法解析

本文地址:http://www.codeinn.net/misctech/193863.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有