In Spring, you can use init-method and destroy-method as attribute in bean configuration file for bean to perform certain actions upon initialization and destruction. Alternative to InitializingBean and DisposableBean interface.

Example

Here’s an example to show you how to use init-method and destroy-method.

  1. package com.mkyong.customer.services;
  2. public class CustomerService
  3. {
  4. String message;
  5. public String getMessage() {
  6. return message;
  7. }
  8. public void setMessage(String message) {
  9. this.message = message;
  10. }
  11. public void initIt() throws Exception {
  12. System.out.println("Init method after properties are set : " + message);
  13. }
  14. public void cleanUp() throws Exception {
  15. System.out.println("Spring Container is destroy! Customer clean up");
  16. }
  17. }

File : Spring-Customer.xml, define init-method and destroy-method attribute in your bean.

  1. <beans xmlns="http://www.springframework.org/schema/beans"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://www.springframework.org/schema/beans
  4. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
  5. <bean id="customerService" class="com.mkyong.customer.services.CustomerService"
  6. init-method="initIt" destroy-method="cleanUp">
  7. <property name="message" value="i'm property message" />
  8. </bean>
  9. </beans>

Run it

  1. package com.mkyong.common;
  2. import org.springframework.context.ConfigurableApplicationContext;
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;
  4. import com.mkyong.customer.services.CustomerService;
  5. public class App
  6. {
  7. public static void main( String[] args )
  8. {
  9. ConfigurableApplicationContext context =
  10. new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});
  11. CustomerService cust = (CustomerService)context.getBean("customerService");
  12. System.out.println(cust);
  13. context.close();
  14. }
  15. }

The ConfigurableApplicationContext.close will close the application context, releasing all resources and destroying all cached singleton beans.

Output

  1. Init method after properties are set : i'm property message
  2. com.mkyong.customer.services.CustomerService@47393f
  3. ...
  4. INFO: Destroying singletons in org.springframework.beans.factory.
  5. support.DefaultListableBeanFactory@77158a:
  6. defining beans [customerService]; root of factory hierarchy
  7. Spring Container is destroy! Customer clean up

The initIt() method is called, after the message property is set, and the cleanUp() method is called after the context.close();

Thoughts…

It’s always recommended to use init-method and destroy-method in bean configuration file, instead of implement the InitializingBean and DisposableBean interface to cause unnecessarily coupled your code to Spring.

Spring init-method and destroy-method example的更多相关文章

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

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

  2. spring init method destroy method

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

  3. EurekaClient项目启动报错Invocation of destroy method failed on bean with name 'scopedTarget.eurekaClient': org.springframework.beans.factory.BeanCreationNotAllowedException: Error creating bean with name 'e

    Disconnected from the target VM, address: '127.0.0.1:51233', transport: 'socket' Eureka Client的使用 使用 ...

  4. Invoking destroy method 'close' on bean with name 'dataSource'

    Invoking destroy method 'close' on bean with name 'dataSource' Spring与Mybatis整合时出现的问题,找了一晚上结果是一个属性写错 ...

  5. Spring 通过工厂方法(Factory Method)来配置bean

    Spring 通过工厂方法(Factory Method)来配置bean 在Spring的世界中, 我们通常会利用bean config file 或者 annotation注解方式来配置bean. ...

  6. kendo method:destroy 解决有些在kendo.all.js 的js 库里报错问题

    首先,不得不承认,kendo UI 是个不错的东西,特别对于一个前端开发到行不足的程序猿来说.而在我们使用过程中貌似还是会遇到各种奇怪的问题.比如我们会经常用到对一些控件进行重赋值. destroy ...

  7. Invocation of destroy method failed on bean with name ‘XXXX’

    项目启动报错问题:Invocation of destroy method failed on bean with name 'scopedTarget.eurekaClient': org.spri ...

  8. ServletContext结合Servlet接口中的init()方法和destroy()方法的运用----网站计数器

    我们一般知道Servlet接口中的init()方法在tomcat启动时调用,destroy()方法在tomcat关闭时调用.那么这两个方法到底在实际开发中有什么作用呢?这就是这个随笔主要讲的内容. 思 ...

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

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

随机推荐

  1. poj 2891 Strange Way to Express Integers (扩展gcd)

    题目链接 题意:给k对数,每对ai, ri.求一个最小的m值,令m%ai = ri; 分析:由于ai并不是两两互质的, 所以不能用中国剩余定理. 只能两个两个的求. a1*x+r1=m=a2*y+r2 ...

  2. HDU 4946 共线凸包

    题目大意: 一些点在一张无穷图上面,每个点可以控制一些区域,这个区域满足这个点到达这个区域的时间严格小于其他点.求哪些点能够控制无穷面积的区域. 题目思路: 速度小的控制范围一定有限. 速度最大当且仅 ...

  3. ADODB.Connection 错误 '800a0e7a' 未找到提供程序。该程序可能未正确安装。解决方法!

    [问题描述]调试基于ACCESS+ASP的网站程序的时候,遇到如下错误: ADODB.Connection 错误 '800a0e7a' 未找到提供程序.该程序可能未正确安装. /Inc/Functio ...

  4. 使用Jquery promise 动态引入js文件

    动态加载一个js得方式很多,如下方式: /** *一般方式加载 */ function normalLoadScript(url) { var node = document.createElemen ...

  5. 通过AJAX与ASP.NET结合实现的仿GridView增删改查功能

    jQurey代码部分: 1.    <script type="text/javascript"> 2.            var flag = 0; 3. 4.  ...

  6. linq xml读取

    <?xml version="1.0" encoding="UTF-8" ?> <cache> <chatOld> < ...

  7. 《SPFA算法的优化及应用》——姜碧野(学习笔记)

    一.核心性质:三角不等式.最短路满足d[v]<=d[u]+w(u,v) 二.SPFA两种实现: 常见的是基于bfs的,这是直接对bellman-ford用队列维护.根据最短路的长度最长为(n-1 ...

  8. dynamic_cast,const_cast,static_cast,reinterpret_cast 详解

    如果直接指针直接强转,将只能访问虚函数的内容,而不能访问特定类中的特定成员或方法!!!! 强制类型转换运算符:C++有四种强制类型转换符,分别是dynamic_cast,const_cast,stat ...

  9. Android Broadcast Receiver

    说明 有时候我们在做android系统软件的时候,经常会需要做的事就是开机重新设置上次关机前的状态,当然,我们就会用到这个开机广播: <uses-permission android:name= ...

  10. json化表单数据

    /** * josn化表单数据 * @name baidu.form.json * @function * @grammar baidu.form.json(form[, replacer]) * @ ...