We may sometimes encounter this scenario at work and need to perform certain actions when exiting the container. There are two ways we can choose (in fact, the way we use it in spring springboot). Just Destory-method is configured in XML, Springboot is to be configured. So this is not the way to do this), one is to implement the Disposablebean interface, one is to use @predestroy annotations. OK, let me take a look at two examples below:
Disposablebean InterfaceWe can implement this interface to perform certain operations when the container exits. Examples are as follows:
Packagecom.zkn.learnspringboot.destory;ImportOrg.springframework.beans.factory.DisposableBean;ImportOrg.springframework.boot.ExitCodeGenerator;Importorg.springframework.stereotype.Component;/*** Created by Zkn on 2016/8/14.*/@Component Public classTestimpldisposablebeanImplementsDisposablebean, exitcodegenerator {@Override Public voidDestroy ()throwsException {System.out.println ("<<<<<<<<<<< I was destroyed, ......................>>>>>>>>>. >>>>>> "); System.out.println ("<<<<<<<<<<< I was destroyed, ......................>>>>>>>>>. >>>>>> "); } @Override Public intGetexitcode () {return5; }}
@PreDestroy annotations
We can add this annotation to the method of the class we need, as well as meet our needs.
Packagecom.zkn.learnspringboot.destory;Importorg.springframework.stereotype.Component;ImportJavax.annotation.PreDestroy;/*** Created by Zkn on 2016/8/14.*/@Component Public classTestannotationpredestroy {@PreDestroy Public voiddestory () {System.out.println ("I was destroyed 、、、、、 I was using the @predestory way 、、、、、、"); System.out.println ("I was destroyed 、、、、、 I was using the @predestory way 、、、、、、"); }}
The output results are as follows:
TIPS:exit you can exit by using the features in the IDE. Here I started with a jar started in cmd, the start command is as follows:Java-jar Learnspringboot-0.0.1-snapshot.jar, so I am here to exit with CTRL + C to perform the exit operation. If you use the MVN spring-boot:run to start running, the destroy operation may not be performed.
Call a custom destroy method when Springboot exit service (Exit)