(转)Spring 的 init-method 和 destory-method
背景:今天在项目中看到spring中bean在初始化和注销时候的方法定义,之前没有用过这种方式,在此记录下,方便后期查看!
关于在spring 容器初始化 bean 和销毁前所做的操作定义方式有三种:
第一种:通过@PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作
第二种是:通过 在xml中定义init-method 和 destory-method方法
第三种是: 通过bean实现InitializingBean和 DisposableBean接口
1 通过@PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作
项目结构:

定义相关实现类:
package com.lxw.study01;
/**
* @author lxw
* @describe
* @date 2017年7月25日 下午2:30:53
*/
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy; public class PersonService { private String message; public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
} @PostConstruct
public void init(){
System.out.println("I'm init method using @PostConstrut...."+message);
} @PreDestroy
public void dostory(){
System.out.println("I'm destory method using @PreDestroy....."+message);
} }
定义相关配置文件annotation.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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <!-- <context:component-scan base-package="com.myapp.core.jsr330"/> --> <context:annotation-config /> <bean id="personService" class="com.lxw.study01.PersonService">
<property name="message" value="123"></property>
</bean> </beans>
其中<context:annotation-config />告诉spring 容器采用注解配置:扫描注解配置;
测试类:
package com.lxw.study01;
/**
* @author lxw
* @describe
* @date 2017年7月25日 下午2:29:09
*/
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("annotation.xml"); PersonService personService = (PersonService)context.getBean("personService"); personService.dostory();
} }
运行结果:
I'm init method using @PostConstrut....123
I'm destory method using @PreDestroy.....123
其中也可以通过申明加载org.springframework.context.annotation.CommonAnnotationBeanPostProcessor
类来告诉Spring容器采用的 常用 注解配置的方式:
只需要修改配置文件为:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <!-- <context:component-scan base-package="com.myapp.core.jsr330"/> --> <!-- <context:annotation-config /> --> <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
<bean id="personService" class="com.myapp.core.annotation.init.PersonService">
<property name="message" value="123"></property>
</bean> </beans>
同样可以得到以上测试的输出结果。
2 通过 在xml中定义init-method 和 destory-method方法
项目结构:

在xml中配置 init-method和 destory-method方法,只是定义spring 容器在初始化bean 和容器销毁之前的所做的操作
基于xml的配置只是一种方式:
直接上xml中配置文件,定义SpringBeans.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" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"> <bean id="personService" class="com.lxw.study.PersonService"
scope="singleton" init-method="init" destroy-method="cleanUp" />
</beans>
ps:单例模式,表示spring容器中只存在一个bean,供程序调用
定义PersonService类:
package com.lxw.study;
/**
* @author lxw
* @describe
* @date 2017年7月25日 上午10:53:27
*/
public class PersonService {
private String message; public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
} public void init(){
System.out.println("init");
}
// how validate the destory method is a question
public void cleanUp(){
System.out.println("cleanUp");
}
}
相应的测试类:
package com.lxw.study; import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; /**
* @author lxw
* @describe
* @date 2017年7月25日 上午10:53:59
*/
public class MainTest {
public static void main(String[] args) { AbstractApplicationContext context =new ClassPathXmlApplicationContext("SpringBeans.xml"); PersonService person = (PersonService)context.getBean("personService"); person.setMessage("hello spring01"); PersonService person_new = (PersonService)context.getBean("personService");
person_new.setMessage("hello spring02"); System.out.println(person.getMessage());
System.out.println(person_new.getMessage());
context.registerShutdownHook(); }
}
测试结果:
init
hello spring02
hello spring02
cleanUp
ps:因为是单例模式,所以程序中修改的是同一个bean,(都输出hello spring02)。正因为是单例模式,所以程序中的初始化和销毁只执行一次。
可以看出 init 方法和 clean up方法都已经执行了。
context.registerShutdownHook(); 是一个钩子方法,当jvm关闭退出的时候会调用这个钩子方法,在设计模式之 模板模式中 通过在抽象类中定义这样的钩子方法由实现类进行实现,这里的实现类是AbstractApplicationContext,这是spring 容器优雅关闭的方法。
3 通过bean实现InitializingBean和 DisposableBean接口
项目结构:

定义相应类实现InitializingBean ,DisposableBean 接口
package com.lxw.study02;
/**
* @author lxw
* @describe
* @date 2017年7月25日 下午2:30:53
*/
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean; public class PersonService implements InitializingBean,DisposableBean{ private String message; public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
} @Override
public void destroy() throws Exception {
// TODO Auto-generated method stub
System.out.println("I'm init method using implements InitializingBean interface...."+message); } @Override
public void afterPropertiesSet() throws Exception {
// TODO Auto-generated method stub
System.out.println("I'm init method using implements DisposableBean interface...."+message); } }
定义相应的配置文件annotation02.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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <!-- <context:component-scan base-package="com.myapp.core.jsr330"/> --> <!-- <context:annotation-config /> --> <!-- <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
<bean id="personService" class="com.myapp.core.annotation.init.PersonService">
<property name="message" value="123"></property>
</bean>
--> <bean id="personService" class="com.lxw.study02.PersonService">
<property name="message" value="12345"></property>
</bean> </beans>
测试类:
package com.lxw.study02;
/**
* @author lxw
* @describe
* @date 2017年7月25日 下午2:29:09
*/
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainTest { public static void main(String[] args) { AbstractApplicationContext context = new ClassPathXmlApplicationContext("annotation02.xml"); PersonService personService = (PersonService)context.getBean("personService"); context.registerShutdownHook();
} }
测试结果:
I'm init method using implements DisposableBean interface....12345
I'm init method using implements InitializingBean interface....12345
(转)Spring 的 init-method 和 destory-method的更多相关文章
- java代码中init method和destroy method的三种使用方式
在java的实际开发过程中,我们可能常常需要使用到init method和destroy method,比如初始化一个对象(bean)后立即初始化(加载)一些数据,在销毁一个对象之前进行垃圾回收等等. ...
- Modified Least Square Method and Ransan Method to Fit Circle from Data
In OpenCv, it only provide the function fitEllipse to fit Ellipse, but doesn't provide function to f ...
- 关于.ToList(): LINQ to Entities does not recognize the method ‘xxx’ method, and this method cannot be translated into a store expression.
LINQ to Entities works by translating LINQ queries to SQL queries, then executing the resulting quer ...
- Invalid character found in method name. HTTP method names must be tokens
o.apache.coyote.http11.Http11Processor : Error parsing HTTP request header Note: further occurrenc ...
- SpringBoot:Invalid character found in method name. HTTP method names must be tokens
问题背景 关于SpringBoot应用挂了很久之后,会发生Invalid character found in method name. HTTP method names must be token ...
- Day04 -玩弄Ruby的方法:instance method与class method
前情提要在第三天时,我们解说了如何在class里用include与extend,去使用module的method. Include is for adding methods to an instan ...
- tomcat 启动报错 Invalid character found in method name. HTTP method names must be tokens
解决:Invalid character found in method name. HTTP method names must be tokens 阿里云上弄了一个tomcat,经常半夜发送崩 ...
- [Python] Python 之 function, unbound method 和 bound method
首先看一下以下示例.(Python 2.7) #!/usr/bin/env python # -*- coding: utf-8 -*- class C(object): def foo(self): ...
- Python OOP(2)-static method,class method and instance method
静态方法(Static Method): 一种简单函数,符合以下要求: 1.嵌套在类中. 2.没有self参数. 特点: 1.类调用.实例调用,静态方法都不会接受自动的self参数. 2.会记录所有实 ...
- Postman请求后台报错:Invalid character found in method name. HTTP method names must be tokens
在使用Postman请求后台时Postman出现 开发工具控制台报 信息: Error parsing HTTP request header Note: further occurrences of ...
随机推荐
- Day2 - Python基础2习题集
1.购物车程序 product_list = [ (), (), (), (), (), (), ] shooping_list = [] salary = input("Input you ...
- 排序算法 - 插入排序(Insertion sort)
插入排序对于少量元素的排序是很高效的,而且这个排序的手法在每个人生活中也是有的哦. 你可能没有意识到,当你打牌的时候,就是用的插入排序. 概念 从桌上的牌堆摸牌,牌堆内是杂乱无序的,但是我们摸上牌的时 ...
- 【Python3之面向对象的程序设计】
一.面向对象的程序设计的由来 1.第一阶段:面向机器,1940年以前 最早的程序设计都是采用机器语言来编写的,直接使用二进制码来表示机器能够识别和执行的指令和数据. 简单来说,就是直接编写 0 和 1 ...
- Java IO学习笔记总结
Java IO学习笔记总结 前言 前面的八篇文章详细的讲述了Java IO的操作方法,文章列表如下 基本的文件操作 字符流和字节流的操作 InputStreamReader和OutputStreamW ...
- SICP-1.4-函数设计
何为好的函数 每个函数只完成一个工作 不要做重复工作 如果你多次复制一段代码块,说明你应该进行函数抽象了 定义一般化函数 避免特例化 函数说明 一般通过三引号说明 help调出函数说明 避免过多的参数 ...
- 高考志愿填报:java 软件 程序员 目前的就业现状
大约在17年前,也就是2000年,学计算机专业的学生可以有大部分都进入本专业,并且就业非常容易.哪怕只会office套件,想找个工作也很简单.那时候学计算机就是最热门的行业. 那时候,搞Java的还是 ...
- 【LeetCode】327. Count of Range Sum
题目: Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusiv ...
- 13.localStorage和sessionStorage的区别
HTMl5的sessionStorage和localStorage html5中的Web Storage包括了两种存储方式:sessionStorage和localStorage. sessionSt ...
- 2.如何安装vmvare tools
1.在主页点击虚拟机 重装vmvaretools,接着就会下载tar.gz包 2.cd 到解压包的地方,解压sudo tar zxf ... 3.解压之后会生成一个vmvare-toos-distri ...
- java连接mysql源码
import java.sql.; import java.text.SimpleDateFormat; import java.util.; import java.util.Date; impor ...