(转)Spring 的 init-method 和 destory-method

背景:今天在项目中看到spring中bean在初始化和注销时候的方法定义,之前没有用过这种方式,在此记录下,方便后期查看!

关于在spring 容器初始化 bean 和销毁前所做的操作定义方式有三种:

第一种:通过@PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作

第二种是:通过 在xml中定义init-method 和 destory-method方法

第三种是: 通过bean实现InitializingBean和 DisposableBean接口

1 通过@PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作

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,正因为是单例模式,所以程序中的初始化和销毁只执行一次。

可以看出 init 方法和 clean up方法都已经执行了。

context.registerShutdownHook(); 是一个钩子方法,当jvm关闭退出的时候会调用这个钩子方法,在设计模式之 模板模式中 通过在抽象类中定义这样的钩子方法由实现类进行实现,这里的实现类是AbstractApplicationContext,这是spring 容器优雅关闭的方法。

3 通过bean实现InitializingBean和 DisposableBean接口

时间: 2024-07-28 22:51:44

(转)Spring 的 init-method 和 destory-method的相关文章

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

在java的实际开发过程中,我们可能常常需要使用到init method和destroy method,比如初始化一个对象(bean)后立即初始化(加载)一些数据,在销毁一个对象之前进行垃圾回收等等. 周末对这两个方法进行了一点学习和整理,倒也不是专门为了这两个方法,而是在巩固spring相关知识的时候提到了,然后感觉自己并不是很熟悉这个,便好好的了解一下. 根据特意的去了解后,发现实际上可以有三种方式来实现init method和destroy method. 要用这两个方法,自然先要知道这两

oauth2(spring security)报错method_not_allowed(Request method &#39;GET&#39; not supported)解决方法

报错信息 <MethodNotAllowed> <error>method_not_allowed</error> <error_description>Request method 'GET' not supported</error_description> </MethodNotAllowed> 39是单引号 原因 默认只支持post 解决方法 下载安装postman工具(或其他post工具) 使用post调用 代码增加get的

Invalid character found in method name. HTTP method names must be tokens

  o.apache.coyote.http11.Http11Processor : Error parsing HTTP request header Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level. java.lang.IllegalArgumentException: Invalid character found in method name. HTTP metho

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

静态方法(Static Method): 一种简单函数,符合以下要求: 1.嵌套在类中. 2.没有self参数. 特点: 1.类调用.实例调用,静态方法都不会接受自动的self参数. 2.会记录所有实例的信息,而不是为实例提供行为. 简单说staticmethod 无法访问类属性.实例属性,相当于一个相对独立的方法,跟类其实没什么关系,换个角度来讲,其实就是放在一个类的作用域里的函数而已. #!python2 #-*- coding:utf-8 -*- class A: v1="class ar

LINQ to Entities does not recognize the method &#39;Int32 ToInt32(System.String)&#39; method, and this method cannot be translated into a store expression

if (!string.IsNullOrEmpty(FarmWorkId)) { data = data.Where(p => p.TypeId == Convert.ToInt32(FarmWorkId)); } 解决方法: if (!string.IsNullOrEmpty(FarmWorkId)) { int i = Convert.ToInt32(FarmWorkId); data = data.Where(p => p.TypeId == i); } LINQ to Entities

Spring Boot 进行Bean Validate和Method Validate

SpringBoot在内部通过集成hibernate-validation 已经实现了JSR-349验证规范接口,在SpringBoot项目中只要直接使用就行了. 一般用在Controller中用于验证前端传来的参数. 验证分两种:对封装的Bean进行验证  或者  对方法简单参数的验证 一.进行BeanValidate 1.定义Bean public class ValidBean { @NotNull(message = "名字不能为空") private String name;

learning spring for Init Project (一)

reference:https://spring.io/quickstart 内容概要: 1 .初始化工程: 首先打开Idea软件, File->New->Project,如下图所示: 选中上图Spring Assistant,这是一个插件用来初始化spring工程.点击上图下一步,如下图所示: 点击Next.如下图所示: 选中上图的Web->Spring Web,然后点击Next,如下图所示: 输入项目名称,选项工程存放路径,点击Next. 如下图所示: 等待工程自动下载相关的jar包

display method, edit method, cach display ,security(备查)

Display 方法: 修饰符display所修的方法,其返回值将被作为一个不可以修改的值在form和report上显示.如果你希望这个值可以被编辑,就是要edit方法. <1> Display方法的书写位置: Display修饰符可以被用于以下方法: (1) Table下的方法 (2) Form下的方法 (3) Form data source下的方法 (4) Report下的方法 (5) Report design下的方法 Table下的display方法可以在多个form和report上

解决:Invalid character found in method name. HTTP method names must be tokens

  阿里云上弄了一个tomcat,经常半夜发送崩溃,查看日志发现这个东西,查阅资料发现是Tomcat的header缓冲区大小不够,只需要在server.xml中增加maxHttpHeaderSize字段即可: <Connector URIEncoding="UTF-8" port="8080" protocol="org.apache.coyote.http11.Http11NioProtocol" useBodyEncodingForUR

spring init

DN学院讲师招募     Markdown编辑器轻松写博文     TOP 50 CTO坐镇直招     读文章说感想获好礼 通过Spring @PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作 分类: Spring 2013-03-16 16:48 24901人阅读 评论(1) 收藏 举报 关于在spring  容器初始化 bean 和销毁前所做的操作定义方式有三种: 第一种:通过@PostConstruct 和 @PreDestroy 方法