Bean生命周期

Spring Bean Life Cycle https://www.tutorialspoint.com/spring/spring_bean_life_cycle.htm

The life cycle of a Spring bean is easy to understand. When a bean is instantiated, it may be required to perform some initialization to get it into a usable state. Similarly, when the bean is no longer required and is removed from the container, some cleanup may be required.

Though, there are lists of the activities that take place behind the scene between the time of bean Instantiation and its destruction, this chapter will discuss only two important bean life cycle callback methods, which are required at the time of bean initialization and its destruction.

To define setup and teardown for a bean, we simply declare the <bean> with initmethod and/or destroy-method parameters. The init-method attribute specifies a method that is to be called on the bean immediately upon instantiation. Similarly, destroymethod specifies a method that is called just before a bean is removed from the container.

Initialization callbacks

The org.springframework.beans.factory.InitializingBean interface specifies a single method −

void afterPropertiesSet() throws Exception;

Thus, you can simply implement the above interface and initialization work can be done inside afterPropertiesSet() method as follows −

public class ExampleBean implements InitializingBean {
public void afterPropertiesSet() {
// do some initialization work
}
}

In the case of XML-based configuration metadata, you can use the init-method attribute to specify the name of the method that has a void no-argument signature. For example −

<bean id = "exampleBean" class = "examples.ExampleBean" init-method = "init"/>

Following is the class definition −

public class ExampleBean {
public void init() {
// do some initialization work
}
}

Destruction callbacks

The org.springframework.beans.factory.DisposableBean interface specifies a single method −

void destroy() throws Exception;

Thus, you can simply implement the above interface and finalization work can be done inside destroy() method as follows −

public class ExampleBean implements DisposableBean {
public void destroy() {
// do some destruction work
}
}

In the case of XML-based configuration metadata, you can use the destroy-method attribute to specify the name of the method that has a void no-argument signature. For example −

<bean id = "exampleBean" class = "examples.ExampleBean" destroy-method = "destroy"/>

Following is the class definition −

public class ExampleBean {
public void destroy() {
// do some destruction work
}
}

If you are using Spring's IoC container in a non-web application environment; for example, in a rich client desktop environment, you register a shutdown hook with the JVM. Doing so ensures a graceful shutdown and calls the relevant destroy methods on your singleton beans so that all resources are released.

It is recommended that you do not use the InitializingBean or DisposableBean callbacks, because XML configuration gives much flexibility in terms of naming your method.

Example

Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −

Steps Description
1 Create a project with a name SpringExample and create a package com.tutorialspoint under the src folder in the created project.
2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3 Create Java classes HelloWorld and MainApp under the com.tutorialspoint package.
4 Create Beans configuration file Beans.xml under the src folder.
5 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.

Here is the content of HelloWorld.java file −

package com.tutorialspoint;

public class HelloWorld {
private String message; public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
public void init(){
System.out.println("Bean is going through init.");
}
public void destroy() {
System.out.println("Bean will destroy now.");
}
}

Following is the content of the MainApp.java file. Here you need to register a shutdown hook registerShutdownHook() method that is declared on the AbstractApplicationContext class. This will ensure a graceful shutdown and call the relevant destroy methods.

package com.tutorialspoint;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp {
public static void main(String[] args) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
context.registerShutdownHook();
}
}

Following is the configuration file Beans.xml required for init and destroy methods −

<?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 = "helloWorld" class = "com.tutorialspoint.HelloWorld" init-method = "init"
destroy-method = "destroy">
<property name = "message" value = "Hello World!"/>
</bean> </beans>

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −

Bean is going through init.
Your Message : Hello World!
Bean will destroy now.

Default initialization and destroy methods

If you have too many beans having initialization and/or destroy methods with the same name, you don't need to declare init-method and destroy-method on each individual bean. Instead, the framework provides the flexibility to configure such situation using default-init-method and default-destroy-method attributes on the <beans> element as follows −

<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"
default-init-method = "init"
default-destroy-method = "destroy"> <bean id = "..." class = "...">
<!-- collaborators and configuration for this bean go here -->
</bean> </beans>

 

Bean Life Cycle的更多相关文章

  1. Spring Bean Life Cycle Methods – InitializingBean, DisposableBean, @PostConstruct, @PreDestroy and *Aware interfaces

    Spring Beans are the most important part of any Spring application. Spring ApplicationContext is res ...

  2. spring bean生命周期管理--转

    Life Cycle Management of a Spring Bean 原文地址:http://javabeat.net/life-cycle-management-of-a-spring-be ...

  3. Spring - Bean Definition Bean定义 给容易提供元数据的3方法

    Spring Bean Definition https://www.tutorialspoint.com/spring/spring_bean_definition.htm The objects ...

  4. Spring Bean的一生

    Spring Bean的一生 When you work directly in Java, you can do anything you like with your objects and do ...

  5. Spring面试问题

    什么是Spring框架?Spring框架有哪些主要模块? 使用Spring框架有什么好处? 什么是控制反转(IOC)?什么是依赖注入? 请解释下Spring中的IOC? BeanFactory和App ...

  6. Quarts SimpleTrigger going to BLOCKED state after few repeat intervals--stackoverflow

    question: I am using SimpleTrigger to schedule a job which is supposed to run indefinitely (repeat c ...

  7. 【面试】Spring问答Top 25

    本文由 ImportNew - 一直在路上 翻译自 howtodoinjava.欢迎加入翻译小组.转载请见文末要求. 本人收集了一些在大家在面试时被经常问及的关于Spring的主要问题,这些问题有可能 ...

  8. Spring相框

    1.什么是Spring相框?Spring有哪些主要模块框架? Spring框架是一个为Java应用程序的开发提供了综合.广泛的基础性支持的Java平台. Spring帮助开发人员攻克了开发中基础性的问 ...

  9. Java EE (2) -- Java EE 6 Enterprise JavaBeans Developer Certified Expert(1z0-895)

    Introduction to Java EE Gain an understanding of the Java Platform, Enterprise Edition (Java EE) Exa ...

随机推荐

  1. ffmpeg avformat_open_input返回失败的解决办法

    用ffmpeg做的第一个程序,参考网上的代码,就出现了一些问题,其中avformat_open_input返回失败. 下面是我在网上收集到的失败信息的相关解决: /////////////////// ...

  2. 【转】Linux内核源码分析方法

    一.内核源码之我见 Linux内核代码的庞大令不少人“望而生畏”,也正因为如此,使得人们对Linux的了解仅处于泛泛的层次.如果想透析Linux,深入操作系统的本质,阅读内核源码是最有效的途径.我们都 ...

  3. Oracle从字符串资源中得到想要的数据分析

    [oracle]从字符串资源中得到想要的数据分析需求:订单分析,按照游戏,帐号级别,游戏帐号职业,区服,价格区间分析各款交易数据走势 .目标:订单表(order)处理分析:订单中可以直接读到的标示有游 ...

  4. javascript在字符串中提取网址并替换成超链接

    var str = " http://wasmip.baidu.com.cn/mip/km/archives/km_archives_main/kmArchivesMain.do?metho ...

  5. HEVC有损优化二

    1 .  HEVC有很些设置对速度的提升有很大的帮助,比如m_bUseEarlyCU,m_useEarlySkipDetection等. 把它们设置成true,会有意想不到的效果. 比如对于不同分辨率 ...

  6. swift学习笔记之—自定义函数的规则说明

    原文出自:www.hangge.com  转载请保留原文链接:http://www.hangge.com/blog/cache/detail_517.html 1,无返回值的函数 func test( ...

  7. B-J UI框架(前端异步框架)

    B-JUI 客户端框架 http://xiangzhanyou.com/B-JUI

  8. org.apache.hadoop.ipc.RemoteException(org.apache.hadoop.security.AccessControlException)

    在运行hadoop的程序时,向hdfs中写文件时候,抛出异常信息如下: Caused by: org.apache.hadoop.ipc.RemoteException(org.apache.hado ...

  9. Dubbo(二) -- Simple Monitor

    一.简介 dubbo-monitor-simple是dubbo提供的简单监控中心,可以用来显示接口暴露,注册情况,也可以看接口的调用明细,调用时间等. Simple Monitor挂掉不会影响到Con ...

  10. Effective C++ —— 让自己习惯C++(一)

    条款01 : 视C++为一个语言联邦 C++ == C(C基本语法) + Object-Oriented C++(类,封装,继承,多态……) + Template C++(泛型编程) + STL(容器 ...