How to initialize and destroy beans in Spring?

When creating an instance of a bean you might need to do some initialization to the bean. Likewise, when the bean is no longer needed and removed from the Spring container you might want to do some cleanup routine or destroy the bean.

To do this initialization and destroy routine you can use the init-method anddestroy-method attribute when declaring a bean in spring configuration using the<bean> element.

By defining the init-method and destroy-method it will allow the Spring Container to call the initialization method right after the bean created. And just before the bean removed and discarded from the container, the defined destroy method will be called. Let's see some code snippet as an example.

 

package org.kodejava.example.spring;

public class DemoEngine {
    public void demoInitialize() {
        System.out.println("DemoEngine.demoInitialize");
    }

    public void demoDestroy() {
        System.out.println("DemoEngine.demoDestroy");
    }
}


Below is the Spring configuration file that we use to declare the bean. You'll see in the configuration there are additional attributes that we add to the bean.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 
    <bean id="engine" class="org.kodejava.example.spring.DemoEngine"
          init-method="demoInitialize"
          destroy-method="demoDestroy"/>
 
</beans>


Create a small program to execute our demo:

package org.kodejava.example.spring;
 
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class InitDestroyDemo {
    public static void main(String[] args) {
        ConfigurableApplicationContext context =
                new ClassPathXmlApplicationContext("AutoEngine.xml");
 
        AutoEngine engine = (AutoEngine) context.getBean("engine");
 
        //
        // context.close will remove the bean from the container.
        // This will call our bean destroy method.
        //
        context.close();
    }
}


When you run the program it will print the following output:

DemoEngine.demoInitialize
DemoEngine.demoDestroy


The advantage of using this method to initialize or clean up the bean is that it doesn't mandate our bean to implement or extend any Spring API which will make our bean reusable on other container beside Spring.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值