背景:今天在项目中看到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的更多相关文章

  1. java代码中init method和destroy method的三种使用方式

    在java的实际开发过程中,我们可能常常需要使用到init method和destroy method,比如初始化一个对象(bean)后立即初始化(加载)一些数据,在销毁一个对象之前进行垃圾回收等等. ...

  2. 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 ...

  3. 关于.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 ...

  4. 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 ...

  5. 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 ...

  6. Day04 -玩弄Ruby的方法:instance method与class method

    前情提要在第三天时,我们解说了如何在class里用include与extend,去使用module的method. Include is for adding methods to an instan ...

  7. 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,经常半夜发送崩 ...

  8. [Python] Python 之 function, unbound method 和 bound method

    首先看一下以下示例.(Python 2.7) #!/usr/bin/env python # -*- coding: utf-8 -*- class C(object): def foo(self): ...

  9. Python OOP(2)-static method,class method and instance method

    静态方法(Static Method): 一种简单函数,符合以下要求: 1.嵌套在类中. 2.没有self参数. 特点: 1.类调用.实例调用,静态方法都不会接受自动的self参数. 2.会记录所有实 ...

  10. Postman请求后台报错:Invalid character found in method name. HTTP method names must be tokens

    在使用Postman请求后台时Postman出现 开发工具控制台报 信息: Error parsing HTTP request header Note: further occurrences of ...

随机推荐

  1. 用java实现简单快速的webservice客户端/数据采集器(支持soap1.1和soap1.2标准,支持utf-8编码)

    前言: 用了cxf,axis等各种wbeservice实现库,简单试用了一下动态调用的方式,很不满意,完全无法满足业务的需要,所以自己实现了一个webservice采集客户端,方便动态调用外部webs ...

  2. C++构造函数(一)

    本篇是介绍C++的构造函数的第一篇(共二篇),属于读书笔记,对C++进行一个系统的复习. 构造函数的概念和作用 全局变量未初始化时为0,局部变量未初始化时的值却是无法预测的.这是因为,全局变量的初始化 ...

  3. 深入理解JavaScript中的闭包

    闭包没有想象的那么简单 闭包的概念在JavaScript中占据了十分重要的地位,有不少开发者分不清匿名函数和闭包的概念,把它们混为一谈,我希望借这篇文章能够让大家对闭包有一个清晰的认识. 大家都知道变 ...

  4. SQLServer类型与Java类型转换问题解决

    ResultSet 接口提供用于从当前行获取列值的获取 方法(getBoolean.getLong 等).可以使用列的索引编号或列的名称获取值.一般情况下,使用列索引较为高效.列从 1 开始编号.为了 ...

  5. 如何在phpstorm中安装xdebug调试工具

    用习惯了Visio Studio的调试工具,如果写个php用phpstorm没有调试工具,觉得还缺点什么.接下来就讲解一下如果安装xdebug,最好发现这个插件真好用! 1.下载xdebug.tar: ...

  6. PHP中单引号和双引号的区别

    双引号里面的字段会经过编译器解释,然后再当作HTML代码输出:单引号里面的不进行解释,直接输出: PHP引号使用原则 1.字符串的值用单引号 2.PHP中尽量用单引号,HTML代码全部用双引号 3.在 ...

  7. linux统计cdn日志慢请求

    ./stat_ip.sh live-https.log-0510.gz 1000 #首先用shell脚本可以统计出?日志慢请求查询时间超过?秒对应的ip和对应的调用次数(传两个参数) #!/bin/b ...

  8. 一些爬虫中的snippet

    1.tornado 一个精简的异步爬虫(来自tornado的demo) #!/usr/bin/env python import time from datetime import timedelta ...

  9. Spring Boot1.5.4 连接池 和 事务

    原文:https://github.com/x113773/testall/issues/10 默认连接池---spring Boot中默认支持的连接池有Tomcat.HikariCP .DBCP . ...

  10. [leetcode-575-Distribute Candies]

    Given an integer array with even length, where different numbers in this array represent different k ...