1.6.1.5. Startup and Shutdown Callbacks 启动和停止回调

Spring框架文档介绍了启动和停止回调,包括Lifecycle接口,用于管理对象的启动和停止,如后台进程。Spring托管对象实现Lifecycle接口,当IoC容器接收到启动和停止信号时,会级联调用这些方法。回调顺序基于对象的phase值,较低phase值的对象先启动后停止。停止方法接受回调,确保异步关闭的正确执行。此外,ApplicationContextAware接口提供了刷新和关闭上下文的回调方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 Spring Framework Documentation (5.3.10)

Core

IoC Container, Events, Resources, i18n, Validation, Data Binding, Type Conversion, SpEL, AOP.

   Core Technologies

1. The IoC Container

1.1. Introduction to the Spring IoC Container and Beans(Spring IoC容器和bean简介)

1.2. Container Overview (容器概览)

1.3. Bean Overview (Bean概览)

1.4. Dependencies(依赖)

1.5. Bean Scopes(Bean作用域)

1.6. Customizing the Nature of a Bean (自定义bean的性质)

1.6.1. Lifecycle Callbacks 生命周期回调

1.6.1.1. Initialization Callbacks 初始化回调

1.6.1.2. Destruction Callbacks 销毁回调

1.6.1.3. Default Initialization and Destroy Methods默认初始化和销毁方法

1.6.1.4. Combining Lifecycle Mechanisms (合并生命周期机制)

1.6.1.5. Startup and Shutdown Callbacks 启动和停止回调

1.6.1.6. Shutting Down the Spring IoC Container Gracefully in Non-Web Applications 在非web应用程序优雅地关闭Spr

1.6.2. ApplicationContextAware and BeanNameAware

1.6.3. Other Aware Interfaces 其它Aware接口

1.7. Bean Definition Inheritance(Bean定义继承)

1.8. Container Extension Points (容器扩展点)


下载此文档精编完整版

 No.内容下载地址文档内容目录
1中英双语精编版 第一部分PDF下载内容目录
2中英双语精编版 第二部分PDF下载内容目录
3中文精编版 第一部分PDF下载内容目录
4中文精编版 第二部分PDF下载内容目录

更多章节内容,请点击查看:  Core Technologies


1.6.1.5. Startup and Shutdown Callbacks 启动和停止回调

The Lifecycle interface defines the essential methods for any object that has its own lifecycle requirements (such as starting and stopping some background process):

Lifecycle 接口定义了具有自己生命周期需求的任何对象的基本方法(例如启动和停止某些后台进程):

public interface Lifecycle {

    void start() ;

    void stop() ;

    boolean isRunning() ;
}

ny Spring-managed object may implement the Lifecycle interface. Then, when the ApplicationContext itself receives start and stop signals (for example, for a stop/restart scenario at runtime), it cascades those calls to all Lifecycle implementations defined within that context. It does this by delegating to a LifecycleProcessor, shown in the following listing:

任何Spring托管对象都可以实现Lifecycle 接口。然后,当ApplicationContext 接收到启动和停止信号(start and stop signal)时(例如,对于运行时的停止/重新启动场景(stop/restart scenario)),它将这些调用级联到该上下文中定义的所有Lifecycle 实现。它通过委托给LifecycleProcessor来实现这一点,如下清单所示:

public interface LifecycleProcessor extends Lifecycle {

    void onRefresh() ;

    void onClose() ;
}

Notice that the LifecycleProcessor is itself an extension of the Lifecycle interface. It also adds two other methods for reacting to the context being refreshed and closed.

请注意,LifecycleProcessor 本身就是Lifecycle 接口的扩展。它还添加了另外两种方法,用于响应上下文的刷新和关闭。

Note that the regular org.springframework.context.Lifecycle interface is a plain contract for explicit start and stop notifications and does not imply auto-startup at context refresh time. For fine-grained control over auto-startup of a specific bean (including startup phases), consider implementing org.springframework.context.SmartLifecycle instead.

Also, please note that stop notifications are not guaranteed to come before destruction. On regular shutdown, all Lifecycle beans first receive a stop notification before the general destruction callbacks are being propagated. However, on hot refresh during a context’s lifetime or on stopped refresh attempts, only destroy methods are called.

请注意,常规的org.springframework.context.Lifecycle 接口是显式启动和停止通知的普通约定(plain contract),并不意味着在上下文刷新时自动启动(auto-startup)。对于特定bean(包括启动阶段)自动启动(auto-startup)上的的细粒度控制(fine-grained control),应考虑实现org.springframework.context.SmartLifecycle生命周期。

此外,请注意,停止通知(stop notification)不保证在销毁前发出。在定期关闭时,所有Lifecycle  bean在传播常规销毁回调(destruction callback)之前首先收到停止通知。但是,在上下文的生命周期内进行热刷新(hot refresh)或停止刷新尝试时,只调用destroy方法。

The order of startup and shutdown invocations can be important. If a “depends-on” relationship exists between any two objects, the dependent side starts after its dependency, and it stops before its dependency. However, at times, the direct dependencies are unknown. You may only know that objects of a certain type should start prior to objects of another type. In those cases, the SmartLifecycle interface defines another option, namely the getPhase()  method as defined on its super-interface, Phased. The following listing shows the definition of the Phased interface:

启动和关闭调用的顺序可能很重要。如果任意两个对象之间存在“依赖”关系,则依赖方(dependent side)在其依赖项之后开始,在其依赖项(dependency)之前停止。然而,有时,直接依赖关系是未知的。您可能只知道某一类型的对象应该在另一类型的对象之前启动。在这些情况下,SmartLifecycle 接口定义了另一个选项,即在其超级接口Phased上定义的getPhase()  方法。下表展示了Phased 接口的定义:

public interface Phased {

    int getPhase() ;
}

The following listing shows the definition of the SmartLifecycle interface:

以下列表展示了SmartLifecycle 接口的定义:

public interface SmartLifecycle extends Lifecycle, Phased {

    boolean isAutoStartup() ;

    void stop(Runnable callback);
}

When starting, the objects with the lowest phase start first. When stopping, the reverse order is followed. Therefore, an object that implements SmartLifecycle and whose getPhase()  method returns Integer.MIN_VALUE would be among the first to start and the last to stop. At the other end of the spectrum, a phase value of Integer.MAX_VALUE would indicate that the object should be started last and stopped first (likely because it depends on other processes to be running). When considering the phase value, it is also important to know that the default phase for any “normal” Lifecycle object that does not implement SmartLifecycle is 0. Therefore, any negative phase value indicates that an object should start before those standard components (and stop after them). The reverse is true for any positive phase value.

启动时,具有最低(lowestphase的对象首先启动。停止时,按相反的顺序进行。因此,实现SmartLifecycle 且其getPhase() 方法返回 Integer.MIN_VALUE的对象将首先启动,最后停止。在频谱的另一端,Integer.MAX_VALUEphase值表示对象应该最后启动,然后首先停止(可能是因为它取决于要运行的其他进程)。在考虑phase值时,还必须知道未实现SmartLifecycle 的任何“正常”Lifecycle 对象的默认phase0。因此,任何负phase值都表示对象应在这些标准组件之前启动(并在它们之后停止)。对于任何正phase值,情况正好相反。

The stop method defined by SmartLifecycle accepts a callback. Any implementation must invoke that callback’s run()  method after that implementation’s shutdown process is complete. That enables asynchronous shutdown where necessary, since the default implementation of the LifecycleProcessor interface, DefaultLifecycleProcessor, waits up to its timeout value for the group of objects within each phase to invoke that callback. The default per-phase timeout is 30 seconds. You can override the default lifecycle processor instance by defining a bean named lifecycleProcessor within the context. If you want only to modify the timeout, defining the following would suffice:

SmartLifecycle 定义的停止方(stop method)法接受回调。任何实现都必须在该实现的关闭过程(implementation’s shutdown process)完成后调用该回调函数的run() 方法。这将在必要时启用异步关闭(asynchronous shutdown),因为LifecycleProcessor 接口的默认实现DefaultLifecycleProcessor将等待每个phase中的对象组调用该回调,直到其超时值(timeout value)为止。默认每phase超时(default per-phase timeout)为30秒。通过在上下文中定义名为lifecycleProcessor bean,可以覆盖默认的生命周期处理器实例(default lifecycle processor instance)。如果只想修改超时,定义以下内容就足够了:

<bean id="lifecycleProcessor" class="org.springframework.context.support.DefaultLifecycleProcessor">
    <!-- timeout value in milliseconds -->
    <property name="timeoutPerShutdownPhase" value="10000"/>
</bean>

As mentioned earlier, the LifecycleProcessor interface defines callback methods for the refreshing and closing of the context as well. The latter drives the shutdown process as if stop()  had been called explicitly, but it happens when the context is closing. The 'refresh' callback, on the other hand, enables another feature of SmartLifecycle beans. When the context is refreshed (after all objects have been instantiated and initialized), that callback is invoked. At that point, the default lifecycle processor checks the boolean value returned by each SmartLifecycle object’s isAutoStartup()  method. If true, that object is started at that point rather than waiting for an explicit invocation of the context’s or its own start()  method (unlike the context refresh, the context start does not happen automatically for a standard context implementation). The phase value and any “depends-on” relationships determine the startup order as described earlier.

如前所述,LifecycleProcessor 接口还定义了用于刷新和关闭(refreshing and closing)上下文的回调方法。后者驱动关闭过程,就像是显式调用了stop() ,但它发生在上下文关闭时。另一方面,“刷新”('refresh')回调启用SmartLifecycle bean的另一项功能。当上下文被刷新时(在所有对象被实例化和初始化之后),该回调被调用。此时,默认生命周期处理器(default lifecycle processor)将检查每个SmartLifecycle 对象的isAutoStartup () 方法返回的布尔值。如果为true,则该对象将在该点启动,而不是等待显式调用上下文或其自身的start() 方法(与上下文刷新不同,对于标准上下文实现,上下文启动不会自动发生)。如前所述,phase 值和相关“依赖”关系决定启动顺序(startup orde)。

要实现串口端口扫描的MATLAB App,可以按照以下步骤进行操作: 1. 在MATLAB App Designer中创建一个新的App。 2. 在App Designer中添加一个按钮或者其他控件,用于触发串口端口扫描。 3.回调函数中,使用MATLAB的serial函数来扫描所有可用的串口端口。 4. 将扫描结果显示在App中的列表或者其他控件中。 下面是一个示例代码,可以实现串口端口扫描: ```matlab classdef SerialPortScanner < matlab.apps.AppBase % Properties that correspond to app components properties (Access = public) UIFigure matlab.ui.Figure ScanButton matlab.ui.control.Button PortList matlab.ui.control.ListBox end % Callbacks that handle component events methods (Access = private) % Button pushed function: ScanButton function scanButtonPushed(app, event) % Scan for available serial ports ports = seriallist(); % Display the list of available ports app.PortList.Items = ports; end end % App initialization and construction methods (Access = private) % Create UIFigure and components function createComponents(app) % Create UIFigure and set properties app.UIFigure = uifigure('Visible', 'off'); app.UIFigure.Position = [100 100 640 480]; app.UIFigure.Name = 'Serial Port Scanner'; % Create ScanButton app.ScanButton = uibutton(app.UIFigure, 'push'); app.ScanButton.ButtonPushedFcn = createCallbackFcn(app, @scanButtonPushed, true); app.ScanButton.Position = [270 210 100 22]; app.ScanButton.Text = 'Scan'; % Create PortList app.PortList = uilistbox(app.UIFigure); app.PortList.Position = [240 260 150 150]; % Show the figure after all components are created app.UIFigure.Visible = 'on'; end end % App startup and shutdown methods (Access = private) % Close request function: UIFigure function figureCloseRequest(app, event) % Delete the figure when closing delete(app.UIFigure); end end % App creation and deletion methods (Access = public) % Construct app function app = SerialPortScanner % Create UIFigure and components createComponents(app) % Register the app with App Designer registerApp(app, app.UIFigure) % Execute the startup function runStartupFcn(app, @startupFcn) % Show the figure if nargout == 0 clear app return end end % Code that executes before app deletion function delete(app) % Delete UIFigure when app is deleted delete(app.UIFigure) end end end ``` 这个App包括一个按钮一个列表控件,点击按钮可以扫描所有可用的串口端口,并将结果显示在列表中。可以根据需要对这个App进行自定义扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

月满闲庭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值