Three ways to use Init method and destroy method in Java code

Source: Internet
Author: User

In the actual development of Java, we may often need to use the Init method and destroy method, such as initializing an object (bean) immediately after initializing (loading) Some data, garbage collection before destroying an object, and so on.
The two methods at the weekend to learn and organize a little, not specifically for these two methods, but in the consolidation of spring-related knowledge of the time mentioned, and then feel that they are not very familiar with this, then a good understanding.
Based on a deliberate understanding, there are actually three ways to implement the Init method and the Destroy method.
To use these two methods, it is natural to know what these two methods are for. And the literal meaning is easy to understand, one is to load, and one is to destroy.
Below is the official Code demo three ways to create:
One, @Bean annotation method:
The first thing to do is to create a class with at least two methods, one method acting as the Init method and the other acting as the Destroy method.

package springtest2; Public  class  Test1 {public  void  init  () {system.    Out . println ();        } public  test1  () {super (); System.    out . println ( "constructor 1" ); } public  void   Destroy  () {system.    Out . println (); }}

The

is obviously just an ordinary Java class, with one parameterless construct and two other methods.
Note that here the Init and destroy two method names are actually can be arbitrarily obtained, do not call this also no problem, but is a kind of convention commonly known, is generally called.
In addition, we also know that this construction method is also not possible, because it will be implicitly created automatically, but in order to see more clearly when Init and destroy is executed, we will display the write out. The
creates this class so that we can specify two methods using @bean annotations to make them effective.

package  Springtest2;import  Org.springframework.context.annotation.Bean; import  Org.springframework.context.annotation.ComponentScan; import  org.springframework.context.annotation.configuration; @Configuration   @ComponentScan  (  "SpringTest2" ) public  class  configtest  {   @Bean  (Initmethod =  "Init" , Destroymethod =  "destroy" ) Test1 test1 () {return new  Test1 (); }}

The @configguration annotation here is to tell spring that the class is a configuration class, equivalent to our XML file, @ComponentScan is to specify a package that needs to be scanned by spring, equivalent to the context in the XML: The Component-scan property.
and the Initmethod and destroymethod behind @bean are declaring that this is a baen and specifying both the Init and Destroy methods, and the method name is optional from the function implementation.
Here we have written in the first way, in order to verify the success or not, then write a main method to verify:

package springTest2;import org.springframework.context.annotation.AnnotationConfigApplicationContext;publicclass MainTest {    publicstaticvoidmain(String[] args) {        new AnnotationConfigApplicationContext(ConfigTest.class);                System.out.println("#################################");        context.close();    }}

Results after running

As you can see in the print order, the first is the constructor, which is the creation of the bean, followed by Init, and then the destroy before context.close to destroy the bean.

Second, the Way of JSR-250 annotations (need to import JSR250-API jar package):
The first is still to create a Java class that has three methods, including a constructor method:

 PackageSpringTest2;ImportJavax.annotation.PostConstruct;ImportJavax.annotation.PreDestroy; Public  class Test2 {    @PostConstruct     Public void Init() {System.out.println ("This is init method2"); } Public Test2() {Super(); System.out.println ("Constructor 2"); }@PreDestroy     Public void Destroy() {System.out.println ("This is destroy Method2"); }}

Obviously, unlike the previous class, there are two annotations added to the Init and destroy methods, the same as the Initmethod after the top @bean, and @predestroy is the same as Destroymethod.
Now that there is a difference, the Init method and the Destroy method have been specified, then there will be a difference in the declaration of the Bean later, and there is no need to specify it again:

package springTest2;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;@Configuration@ComponentScan("springTest2")publicclass ConfigTest {    @Bean    Test2 test2() {        returnnew Test2();    }}

So, as you can simply declare in the code, this is a bean, and the two annotations on top of the class are the same as in the previous example.
Test again:

package springTest2;import org.springframework.context.annotation.AnnotationConfigApplicationContext;publicclass MainTest {    publicstaticvoidmain(String[] args) {        new AnnotationConfigApplicationContext(ConfigTest.class);                System.out.println("#################################");        context.close();    }}

The results are as follows:

Third, the way of XML configuration:
This is actually the same as the first one, except for a slight change in the details, first of all the Java classes are created exactly the same way:

Package springTest2; Public classTEST3 { Public void Init() {System. out. println ("This is init method3"); } Public Test3() {super (); System. out. println ("Constructor 3"); } Public void Destroy() {System. out. println ("This is destroy Method3"); } Public void Test() {System. out. println ("TESTTTTTTTT"); }}

The difference is that the first example uses annotations to tell spring that the class is equivalent to a configuration file, and here is the actual configuration file Spring.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" xsi:schemalocation="Http://www.springframework.org/schema/beans http://www.springframework.org/ Schema/beans/spring-beans.xsd ">              <bean id="Initordestroytest" class="Springtest2.test3"  Init-method="init" destroy-method="Destroy"></Bean></Beans>

This configuration is probably the simplest configuration in Spring.xml, except for the necessary file header, there is only one bean, and the bean inside is only ID,CALSS and Init and Destroy methods.
Because simple, so at a glance, the ID is only for other references, class is to specify the class of the bean, and the back two properties are identical to when declared with @bean.
Since there is an XML configuration that declares the bean and specifies two methods, it will need a little bit of change when testing:

package springTest2;import org.springframework.context.support.ClassPathXmlApplicationContext;publicclass MainTest {    publicstaticvoidmain(String[] args) {        new ClassPathXmlApplicationContext("spring.xml");        System.out.println("#################################");        context1.close();    }}

The difference is that the configuration file is loaded directly instead of the Java class, using Classpathxxmlapplicationcontext instead of Annotationconfigapplicationcontext.
The results are as follows:

One thing to note here is that, in the case of an actual web application, the bean can be loaded with a configuration similar to the following in XML. Init method:

<Servlet-name>Dispatcher</servlet-name>      <Servlet-class>Org.Springframework.Web.Servlet.Dispatcherservlet</servlet-class>      <Init-param>        <Param-name>Contextconfiglocation</param-name>        <Param-value>Classpath:spring.XML</param-value>      </init-param>      <Load-on-startup>1</load-on-startup>    </servlet>    <Servlet-mapping>      <Servlet-name>Dispatcher</servlet-name>      <Url-pattern>/</url-pattern>    </servlet-mapping> 

Then launch the Tomcat results as follows:

There is no call to destroy method here, because spring itself requires us to manually invoke the method of destroying the bean, as in the preceding example Context.close.
If you do not call this method manually, the bean will not be destroyed, and it will not call the Destroy method, which is why the startup tomcat only prints the contents of the constructor and Init methods after it is configured here in Web. Xml.

Examples are simple, and a simple example of comparison may be able to further understand the relevant knowledge, understanding of the actual application can be better in the selection and integration.

Three ways to use Init method and destroy method in Java code

Related Article

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.