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 interface We can implement this interface to perform certain operations when the container exits. Examples are as follows:
Package com.zkn.learnspringboot.destory; Import Org.springframework.beans.factory.DisposableBean; Import Org.springframework.boot.ExitCodeGenerator; Import org.springframework.stereotype.Component; /** * Created by Zkn on 2016/8/14. */ @Component Public class Testimpldisposablebean implements Disposablebean, Exitcodegenerator { @ Override public Void Destroy () throws Exception { System.out.println ("<<<<<<<<< << I was destroyed by ......................>>>>>>>>>>>>>>> "); System.out.println ("<<<<<<<<<<< I was destroyed ......................>>>> >>>>>>>>>>> "); } @Override public int Getexitcode () { return 5; } }
@PreDestroy Annotations We can add this annotation to the method of the class we need, as well as meet our needs.
Package com.zkn.learnspringboot.destory; Import org.springframework.stereotype.Component; Import Javax.annotation.PreDestroy; /** * Created by Zkn on 2016/8/14. * /@Component public class Testannotationpredestroy { @PreDestroy public void Destory () { 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 is as follows: TIPS: Quitting 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.
transferred from: http://blog.csdn.net/zknxx/article/details/52204036
Call a custom destroy method when Springboot exit service (Exit)