背景:今天在项目中看到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. htm语言的语法基础及规则

    HTML的主要语法是元素和标签.元素是符合DTD(文档类型定义)的文档组成部分,如title(文档标题).IMG(图象).table(表格)等等.元素名不区分大小写的.HTML用标签来规定元素的属性和 ...

  2. docker疑难解答 -- 设置远程服务监听

    环境: ubuntu 16.04 tls docker version 17.05.0-ce ========================= 今天想要搭建一个多主机的集成docker环境,但是我最 ...

  3. flask 扩展之 -- flask-login

    一. 使用 Werkzeug 实现密码散列. generate_password_hash(password, method=pbkdf2:sha1, salt_length=8) 将原始密码作为输入 ...

  4. java 类变量的初始化

    有代码如下:class Price{    final static Price INSTANCE = NEW Price(2.8);    static double initPrice = 20; ...

  5. Scheme实现二叉查找树及基本操作(添加、删除、并、交)

    表转化成平衡二叉树 其中有一种分治的思想. (define (list->tree elements) (define (partial-tree elts n) (if (= n 0) (co ...

  6. 【踩坑记录】记一次MySQL主从复制延迟的坑

    最近开发中遇到的一个MySQL主从延迟的坑,记录并总结,避免再次犯同样的错误. 情景 一个活动信息需要审批,审批之后才能生效.因为之后活动要编辑,编辑后也可能触发审批,审批中展示的是编辑前的活动内容, ...

  7. 利用jenkins做项目的自动化部署

    最近领导要求上海本地的项目需要使用进jenkins实现自动化部署,以便可以直接将项目移交给运维的同学,减轻开发的工作量.记录下这次爬坑的过程. 一.前言 Jenkins是基于Java开发的一种持续集成 ...

  8. VS2017专业版和企业版激活密钥

    VS2017专业版和企业版激活密钥 Professional: KBJFW-NXHK6-W4WJM-CRMQB-G3CDH Enterprise: NJVYC-BMHX2-G77MM-4XJMR-6Q ...

  9. Chrome debug tooltip having scrollbars

    谷歌浏览器debugger,查看变量值,出现滚动条无法查看到具体的值 I had the same problem and found your post. I went as far as rein ...

  10. Example018主页加载时获取焦点

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...