In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
In this issue, the editor will bring you about the use of SmartLifecycle in Spring. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article!
Spring SmartLifecycle usage
Spring SmartLifecycle executes after all bean of the container has been loaded and initialized
When developing with Spring, we all know that all bean is centrally managed by the Spring container, including the loading and initialization of each bean.
Sometimes we need to load and initialize all the bean in Spring and then perform some tasks or start the required asynchronous services so that we can use SmartLifecycle to do this.
SmartLifecycle is an interface
When the Spring container loads all the bean and finishes initialization, it then calls back the corresponding method (the start () method) in the class that implements the interface.
Import org.springframework.context.SmartLifecycle;import org.springframework.stereotype.Component;/** * SmartLifecycle test * * / @ Componentpublic class TestSmartLifecycle implements SmartLifecycle {private boolean isRunning = false; / * 1. We mainly start tasks or other asynchronous services in this method, such as opening MQ to receive messages * 2. This method is called when the context is refreshed (after all objects have been instantiated and initialized), and the default lifecycle handler checks the Boolean value returned by the isAutoStartup () method of each SmartLifecycle object. * if "true", the method is called instead of waiting for its own start () method to be explicitly called. * / @ Override public void start () {System.out.println ("start"); / / after executing other services, you can modify isRunning = true isRunning = true;} / * if there are multiple classes in the project that implement the interface SmartLifecycle, the start of these classes will be executed from small to large according to the return value of the getPhase method. * for example: 1 to 2,-1 to 0. The execution order of the stop method is the opposite. The stop method of the larger class returned by getPhase is called first, and the smaller one is called later. * / @ Override public int getPhase () {/ / defaults to 0 return 0;} / * * decides whether to execute the start method based on the return value of this method. * the start method is executed automatically when true is returned, but not when false is returned. * / @ Override public boolean isAutoStartup () {/ / default is false return true;} / * 1. The start method is executed only if the method returns false. * 2. The stop (Runnable callback) or stop () method is executed only if the method returns true. * / @ Override public boolean isRunning () {/ / returns a method unique to the false return isRunning;} / * SmartLifecycle subclass by default. This method will only be called when the isRunning method returns true. * / @ Override public void stop (Runnable callback) {System.out.println ("stop (Runnable)"); / / if you want isRunning to return true and need to execute the stop method, don't forget to call callback.run (). / / otherwise, when your program exits, Spring's DefaultLifecycleProcessor will think that your TestSmartLifecycle is not completed without stop, and the program will not end automatically after waiting for a certain amount of time (the default timeout is 30 seconds). / / PS: if you want to modify this default timeout, you can do it as follows. Of course, the following code is a reference in the form of a springmvc configuration file, which is naturally not done by configuring xml in SpringBoot. This is just a way of thinking. / / callback.run (); isRunning = false;} / * * the method of the subclass of the interface Lifecycle, which is executed only by subclasses other than SmartLifecycle. * 1. This method works only for classes that directly implement interface Lifecycle, but not for classes that implement SmartLifecycle interface. * 2. The only difference between method stop () and method stop (Runnable callback) is that the latter is exclusive to the SmartLifecycle subclass. * / @ Override public void stop () {System.out.println ("stop"); isRunning = false;}} SmartLifecycle interpretation
Org.springframework.context.SmartLifecycle interpretation
1. Interface definition / * * An extension of the {@ link Lifecycle} interface for those objects that require to * be started upon ApplicationContext refresh and/or shutdown in a particular order. * The {@ link # isAutoStartup ()} return value indicates whether this object should * be started at the time of a context refresh. The callback-accepting * {@ link # stop (Runnable)} method is useful for objects that have an asynchronous * shutdown process. Any implementation of this interface must invoke the * callback's run () method upon shutdown completion to avoid unnecessary delays * in the overall ApplicationContext shutdown. * *
This interface extends {@ link Phased}, and the {@ link # getPhase ()} method's * return value indicates the phase within which this Lifecycle component should * be started and stopped. The startup process begins with the lowest * phase value and ends with the highest phase value (Integer.MIN_VALUE * is the lowest possible, and Integer.MAX_VALUE is the highest possible). The * shutdown process will apply the reverse order. Any components with the * same value will be arbitrarily ordered within the same phase. * *
Example: if component B depends on component A having already started, then * component A should have a lower phase value than component B. During the * shutdown process, component B would be stopped before component A.
Any explicit "depends-on" relationship will take precedence over * the phase order such that the dependent bean always starts after its * dependency and always stops before its dependency. * *
Any Lifecycle components within the context that do not also implement * SmartLifecycle will be treated as if they have a phase value of 0. That * way a SmartLifecycle implementation may start before those Lifecycle * components if it has a negative phase value, or it may start after * those components if it has a positive phase value. * *
Note that, due to the auto-startup support in SmartLifecycle, * a SmartLifecycle bean instance will get initialized on startup of the * application context in any case. As a consequence, the bean definition * lazy-init flag has very limited actual effect on SmartLifecycle beans. * * @ author Mark Fisher * @ since 3.0 * @ see LifecycleProcessor * @ see ConfigurableApplicationContext * / public interface SmartLifecycle extends Lifecycle, Phased {/ * Returns {@ code true} if this {@ code Lifecycle} component should get * started automatically by the container at the time that the containing * {@ link ApplicationContext} gets refreshed. *
A value of {@ code false} indicates that the component is intended to * be started through an explicit {@ link # start ()} call instead, analogous * to a plain {@ link Lifecycle} implementation. * @ see # start () * @ see # getPhase () * @ see LifecycleProcessor#onRefresh () * @ see ConfigurableApplicationContext#refresh () * / boolean isAutoStartup (); / * Indicates that a Lifecycle component must stop if it is currently running. *
The provided callback is used by the {@ link LifecycleProcessor} to support * an ordered, and potentially concurrent, shutdown of all components having a * common shutdown order value. The callback must be executed after * the {@ code SmartLifecycle} component does indeed stop. *
The {@ link LifecycleProcessor} will call only this variant of the * {@ code stop} method; I.e. {@ link Lifecycle#stop ()} will not be called for * {@ code SmartLifecycle} implementations unless explicitly delegated to within * the implementation of this method. * @ see # stop () * @ see # getPhase () * / void stop (Runnable callback);}
As can be seen from the comments document:
1. It is an extension of the interface Lifecycle and will be called when the application context class ApplicationContext executes refresh and/or shutdown
2. The value returned by the method isAutoStartup () determines whether the current entity object will be called when the application context class ApplicationContext executes refresh
3. The stop (Runnable) method is used to call the stop method of Lifecycle
4. The return value of getPhase () is used to set the execution priority of LifeCycle: the smaller the value, the higher the priority.
5. IsRunning () determines whether to call the start () method.
2. Apply public class SmartLifecycleImpl implements SmartLifecycle {private Boolean isRunning = false; @ Override public boolean isAutoStartup () {return true;} @ Override public void stop (Runnable callback) {callback.run ();} @ Override public void start () {System.out.println ("SmartLifecycleImpl is starting...."); isRunning = true } @ Override public void stop () {System.out.println ("SmartLifecycleImpl is stopped.");} / * * it is used to determine whether to execute the start () method before it is executed. When true is returned, the start () method does not execute * / @ Override public boolean isRunning () {return isRunning;} @ Override public int getPhase () {return 0;}}.
Startup class
Public class ProviderBootstrap {public static void main (String [] args) throws Exception {AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext (ProviderConfiguration.class); context.start (); System.in.read ();} @ Configuration static class ProviderConfiguration {@ Bean public SmartLifecycleImpl getSmartLifecycleImpl () {return new SmartLifecycleImpl ();}
You can see that after the class SmartLifecycleImpl is submitted to the spring container, the method body of the start () method is output when it is started.
This is how the editor shares the usage of SmartLifecycle in Spring. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.