"Spring Combat"--4 The Bean's init and destroy methods in spring

Source: Internet
Author: User
Tags ticket

This article focuses on the operations that are added in spring by configuring the Init-method and Destroy-method methods to implement the initialization and destruction of beans.

In Java, we don't need to manage memory or variables, and in C or C + +, you can create and delete variables or objects in the form of new and delete. In spring, if you want to initialize and end a bean with a certain operation, you can do so using the two methods described above.

Before introducing these two methods, the reader needs to understand the life cycle of the bean in spring, and the two most commonly used lifecycles are: Singleton and prototype.

Singleton, a single case

In an application context container, all threads or objects get the same instance by Getbean the bean with the specified ID.

This kind of bean instance is entirely controlled by the application context container to control the declaration period, and the user gets the same instance whenever and wherever it is obtained.

For example, there is only one Diaoyu island, Japan says it is theirs, China says it is Chinese. Although there are disputes between the two parties, they feel that they have ownership, but there is only one Diaoyu island, so what we call the Diaoyu Island is the same island as Japan said:

Prototype, prototype

This type of bean creates a new instance each time, and the life cycle of the instance is controlled by the application context only for its initialization and assembly, and once the initialization succeeds, the control is handed over to the user.

A common scenario, such as a ticket or a movie ticket bean instance, should be a new instance each time because a ticket belongs to the same person.

  

By explaining the life cycle of the above, we can see that, when we use the Init-method and Destroy-method methods in spring, the Destroy-method only works in the default case, Singleton mode.

Here is a small example, do a verification:

For example, a stage bean, we want to turn on the lights before using the stage, turn off the lights after the stage is used, and then remove the stage. You can specify the method by Init-method and Destroy-method.

Package Com.spring.test.initdesotry; Public classStage { Public voidperform () {System. out. println ("The show begins ..."); }     Public voidturnonlight () {System. out. println ("before the show starts, turn on the lights ..."); }     Public voidturnofflight () {System. out. println ("turn off the lights before the show is over ..."); }}

Configure Bean.xml

<?xml version="1.0"encoding="UTF-8"? ><beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="Http://www.springframework.org/schema/beans"xsi:schemalocation="Http://www.springframework.org/schema/beanshttp//www.springframework.org/schema/beans/spring-beans-3.0.xsd "><bean id="Stage" class="Com.spring.test.initdesotry.Stage"Scope="prototype"//Note that if it is singleton or there is no such sentence (the default), the Destroy-method specified method will be executed, if the current prototype does not trigger the execution of the DestroymethodInit-method="Turnonlight"Destroy-method="Turnofflight"/></beans>

In the main function, do not forget to apply the closure of the context container, only in this way, will start Destroy-method execution.

Package Com.spring.test.initdesotry;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.ClassPathXmlApplicationContext; Public classTest { Public Static voidMain (string[] args) {ApplicationContext ctx=NewClasspathxmlapplicationcontext ("Bean.xml"); Stage Stage= (Stage) Ctx.getbean ("Stage");        Stage.perform (); ((Classpathxmlapplicationcontext) CTX). Close ();//Close the application context container, and don't forget the phrase}}

When the bean is in singleton mode or by default, the following results are obtained:

January -, - 1: -: thepm Org.springframework.context.support.AbstractApplicationContext preparerefresh Info: Refreshing org[email Protected]4f5cb20e:startup Date [Sun Jan -  -: -: theCst -]; Root of context hierarchy January -, - 1: -: thepm Org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadbeandefinitions Info: Loading XML bean Definitions from classpath resource [bean.xml] January -, - 1: -: thepm Org.springframework.beans.factory.support.DefaultListableBeanFactory preinstantiatesingletons Info: Pre-instantiating singletonsinchorg.s[email protected]68df6513:defining beans [duke,sonnet29,poeticduke,thestage,stage]; root of Factory Hierarchy before the show starts, turn on the lights ... The show begins ... January -, - 1: -: thepm Org.springframework.context.support.AbstractApplicationContext doclose Info: Closing org[email protected] 4f5cb20e:startup Date [Sun Jan -  -: -: theCst -]; Root of context hierarchy January -, - 1: -: thepm Org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroysingletons Info: destroying Singletonsinchorg.s[email protected]68df6513:defining beans [duke,sonnet29,poeticduke,thestage,stage]; root of Factory Hierarchy before the end of the show, turn off the lights ...

When it is prototype mode, the following results are obtained:

January -, - 1: to: +pm Org.springframework.context.support.AbstractApplicationContext preparerefresh Info: Refreshing org[email Protected]4eadddd6:startup Date [Sun Jan -  -: to: +Cst -]; Root of context hierarchy January -, - 1: to: +pm Org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadbeandefinitions Info: Loading XML bean Definitions from classpath resource [bean.xml] January -, - 1: to: +pm Org.springframework.beans.factory.support.DefaultListableBeanFactory preinstantiatesingletons Info: Pre-instantiating singletonsinchorg.s[email protected]2264f82f:defining beans [duke,sonnet29,poeticduke,thestage,stage]; root of Factory Hierarchy before the show starts, turn on the lights ... The show begins ... January -, - 1: to: +pm Org.springframework.context.support.AbstractApplicationContext doclose Info: Closing org[email protected] 4eadddd6:startup Date [Sun Jan -  -: to: +Cst -]; Root of context hierarchy January -, - 1: to: +pm Org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroysingletons Info: destroying SingletonsinchOrg.s[email protected]2264f82f:defining beans [duke,sonnet29,poeticduke,thestage,stage]; Root of Factory hierarchy
Reference

1 "Spring in Action"

2 Spring in Init-method and Destroy-method

"Spring Combat"--4 The Bean's init and destroy methods in spring

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.