[英]Why the concept of starting and stopping beans in spring
可以完成bean初始化/清除的不同方法。 也有其他事件機制。 伴隨着所有這些,spring為什么具有啟動上下文的概念,我相信它會調用bean的相應start和stop方法。
為了進行測試,我有一段看起來像這樣的代碼-
public class Car implements InitializingBean, DisposableBean, SmartLifecycle {
private Engine engine;
private volatile boolean isRunning = false;
@Override
public void afterPropertiesSet() throws Exception {
logger.debug("Car -- afterPropertiesSet");
}
@Override
public void destroy() throws Exception {
logger.debug("Car -- destroy");
}
@PostConstruct
public void postConstruction() {
logger.debug("Car -- postConstruct");
}
@PreDestroy
public void preDestruction() {
logger.debug("Car -- preDestroy");
}
@Override
public void stop() {
//Note that this stop notification is not guaranteed to come before destruction: On regular shutdown,
//Lifecycle beans will first receive a stop notification before the general destruction callbacks are being propagated;
//however, on hot refresh during a context's lifetime or on aborted refresh attempts, only destroy methods will be called.
logger.debug("Car -- stop");
isRunning = false;
}
@Override
public boolean isRunning() {
//Check whether this component is currently running.
//In the case of a container, this will return true only if all components that apply are currently running.
logger.debug("Car -- isRunning");
return isRunning;
}
@Override
public int getPhase() {
//Return the phase value of this object.
logger.debug("Car -- getPhase");
return 10;
}
@Override
public boolean isAutoStartup() {
//Returns true if this Lifecycle component should get started automatically by the container
//A value of false indicates that the component is intended to be started through an explicit start() call instead,
//analogous to a automatic Lifecycle.
logger.debug("Car -- isAutoStartup");
return false;
}
@Override
public void stop(Runnable callback) {
logger.debug("Car -- stop - async");
isRunning = false;
try {
//Sleeping for 10 seconds so that all threads
//get enough time to do their cleanup
TimeUnit.SECONDS.sleep(10);
logger.debug("Wait over");
//Shudown complete. Regular shutdown will continue.
callback.run();
} catch (final InterruptedException e) {
//Looks like we got exception while shutting down,
//log it or do something with it
}
}
@Override
public void start() {
//Start this component.
//Should not throw an exception if the component is already running.
logger.debug("Car -- start");
isRunning = true;
}
}
首先,我為isAutoStartUp返回true值,然后嘗試返回false。 下圖是兩次運行的日志文件的比較。 而且,無論autostartup是true / false,代碼都可以正常運行。
這是當您的bean與服務相關時使用的。 您可能想知道它們何時成功啟動,並且在常規應用程序關閉時也具有正確的關閉過程/清理/拆除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.