最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring?Lifecycle的使用小結(jié)

 更新時間:2022年05月06日 16:11:31   作者:程序員小杰  
這篇文章主要介紹了Spring?Lifecycle的使用,本文結(jié)合實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下

前言

小杰在前面的文章講過可以使用 @PostConstruct、InitializingBean 、xml init、 @PreDestroy 、DisposableBean 、xml destroy來處理 Bean 的初始化和銷毀,上述這些操作是屬于 Bean 生命周期的。

那如果我想在容器本身的生命周期(比如容器啟動、停止)上做一些工作怎么辦呢?Spring 提供了以下接口。

Lifecycle

定義啟動/停止生命周期方法的通用接口。

public interface Lifecycle {
    /**
     * 容器啟動后調(diào)用
     */
	void start();
    /**
     * 容器停止時調(diào)用
     */
	void stop();
        
   /**
     * 檢查此組件是否正在運行。
     * 1. 只有該方法返回false時,start方法才會被執(zhí)行。
     * 2. 只有該方法返回true時,stop()方法才會被執(zhí)行。
     */
	boolean isRunning();
}

自定義Lifecycle實現(xiàn)類

@Component
public class CustomizeLifecycle implements Lifecycle {
	private volatile boolean running = false;
	@Override
	public void start() {
		running = true;
		System.out.println("start ==== ");
	}
	@Override
	public void stop() {
		running = false;
		System.out.println("stop ==== ");
	}
	@Override
	public boolean isRunning() {
		return running;
	}
}

測試

@ComponentScan(basePackages = {"com.gongj.lifecycle"})
public class AppApplication {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext context =
				new AnnotationConfigApplicationContext(AppApplication.class);
		context.start();
		context.stop();
	}
}
結(jié)果:
isRunning ====> false
start ====> 
isRunning ====> true
stop ====> 

使用 Lifecycle這種方式,需要顯示的調(diào)用容器的 startstop方法。 顯得笨重,所以我們使用另外一種方式 :SmartLifecycle。

SmartLifecycle

public interface SmartLifecycle extends Lifecycle, Phased {
	int DEFAULT_PHASE = Integer.MAX_VALUE;
	default boolean isAutoStartup() {
		return true;
	}
	default void stop(Runnable callback) {
		stop();
		callback.run();
	}
	@Override
	default int getPhase() {
		return DEFAULT_PHASE;
	}
}

看到的源碼定義,SmartLifecycle除了繼承Lifecycle之外,還繼承了 Phased。并且新增了幾個方法:

  • isAutoStartup:是否自動啟動。為 treu,則自動調(diào)用start();為 false,則需要顯示調(diào)用 start()。
  • stop:當 isRunning 方法返回 true 時,該方法才會被調(diào)用。
  • getPhase:來自于 Phased 接口,當容器中有多個實現(xiàn)了 SmartLifecycle的類,這個時候可以依據(jù) getPhase方法返回值來決定start 方法、 stop方法的執(zhí)行順序。 start 方法執(zhí)行順序按照 getPhase方法返回值從小到大執(zhí)行,而 stop方法則相反。比如: 啟動時:1 比 3 先執(zhí)行,-1 比 1 先執(zhí)行,退出時:3 比 1 先退出,1 比 -1 先退出。

自定義SmartLifecycle實現(xiàn)類

@Component
public class CustomizeSmartLifecycle implements SmartLifecycle {
	private volatile boolean running = false;
	@Override
	public void start() {
		running = true;
		System.out.println("CustomizeSmartLifecycle start()");
	}
	@Override
	public void stop() {
		System.out.println("CustomizeSmartLifecycle stop()");
		running = false;
	}
	@Override
	public boolean isRunning() {
		System.out.println("CustomizeSmartLifecycle isRunning() ==== " + running);
		return running;
	}
	@Override
	public boolean isAutoStartup() {
		return true;
	}
	@Override
	public void stop(Runnable callback) {
		System.out.println("CustomizeSmartLifecycle stop(Runnable callback)");
		callback.run();
	}
	@Override
	public int getPhase() {
		return 1;
	}
}

將代碼進行啟動,控制臺打印如下內(nèi)容:

public static void main(String[] args) {
    AnnotationConfigApplicationContext context =
        new AnnotationConfigApplicationContext(AppApplication.class);
    //context.start();
    //context.stop();
}
結(jié)果:
CustomizeSmartLifecycle isRunning() ==== false
CustomizeSmartLifecycle start()

發(fā)現(xiàn)并沒有執(zhí)行 stop方法,這是因為容器問題。如果在Spring Boot項目會自動執(zhí)行的,小伙伴可以試一試。

在本例中,還是需要顯示調(diào)用 stop方法。

public static void main(String[] args) {
    AnnotationConfigApplicationContext context =
        new AnnotationConfigApplicationContext(AppApplication.class);
    //context.start();
    context.stop();
}
結(jié)果:
CustomizeSmartLifecycle isRunning() ==== false
CustomizeSmartLifecycle start()
CustomizeSmartLifecycle isRunning() ==== true
CustomizeSmartLifecycle stop(Runnable callback)

發(fā)現(xiàn)執(zhí)行了stop(Runnable callback),并沒有執(zhí)行 stop方法。這是因為當前類是 SmartLifecycle的子類,如果要執(zhí)行 stop方法,需要在stop(Runnable callback)顯示調(diào)用。

@Override
public void stop(Runnable callback) {
    System.out.println("CustomizeSmartLifecycle stop(Runnable callback)");
    stop();
    callback.run();
}
或者
@Override
public void stop(Runnable callback) {
    SmartLifecycle.super.stop(callback);
}

啟動結(jié)果如下:

CustomizeSmartLifecycle isRunning() ==== false
CustomizeSmartLifecycle start()
CustomizeSmartLifecycle isRunning() ==== true
CustomizeSmartLifecycle stop(Runnable callback)
CustomizeSmartLifecycle stop()

注意:在stop(Runnable callback)方法中不要忘記調(diào)用 callback.run()方法。否則DefaultLifecycleProcessor會認為這個SmartLifecycle沒有stop完成,程序會等待一定時間,默認30秒后才會自動結(jié)束。

@Override
public void stop(Runnable callback) {
    System.out.println("CustomizeSmartLifecycle stop(Runnable callback)");
    //stop();
    //callback.run();
}

image-20220108151717136

多個實現(xiàn)類

@Component
public class CustomizeSmartLifecycle2 implements SmartLifecycle {
	private volatile boolean running = false;
	@Override
	public void start() {
		running = true;
		System.out.println("CustomizeSmartLifecycle2 start() =====>");
	}
	@Override
	public void stop() {
		System.out.println("CustomizeSmartLifecycle1 stop() =====>");
		running = false;
	}
	@Override
	public boolean isRunning() {
		System.out.println("CustomizeSmartLifecycle2 isRunning() =====> " + running);
		return running;
	}
	@Override
	public boolean isAutoStartup() {
		return true;
	}
	@Override
	public void stop(Runnable callback) {
		System.out.println("CustomizeSmartLifecycle2 stop(Runnable callback) =====>");
		callback.run();
	}
	@Override
	public int getPhase() {
		return -1;
	}
}

getPhase方法返回 -1。按照前面所說的結(jié)論,那就是 CustomizeSmartLifecycle2start方法會先執(zhí)行,然后 CustomizeSmartLifecycle2stop方法最后執(zhí)行。我們一起來看看執(zhí)行結(jié)果吧!

public static void main(String[] args) {
    AnnotationConfigApplicationContext context =
        new AnnotationConfigApplicationContext(AppApplication.class);
    //context.start();
    context.stop();
}

執(zhí)行結(jié)果:

CustomizeSmartLifecycle2 isRunning() =====> false
CustomizeSmartLifecycle2 start() =====>
CustomizeSmartLifecycle isRunning() ==== false
CustomizeSmartLifecycle start()
CustomizeSmartLifecycle isRunning() ==== true
CustomizeSmartLifecycle stop(Runnable callback)
CustomizeSmartLifecycle2 isRunning() =====> true
CustomizeSmartLifecycle2 stop(Runnable callback) =====>

跟結(jié)論保持一致。

源碼分析

基本的使用就到此結(jié)束啦!我們來結(jié)合源碼分析分析吧!

我們來到 finishRefresh方法的 getLifecycleProcessor().onRefresh();方法。

protected void finishRefresh() {
    // Clear context-level resource caches (such as ASM metadata from scanning).
    clearResourceCaches();
    // Initialize lifecycle processor for this context.
    //為此上下文初始化生命周期處理器
    initLifecycleProcessor();
    // Propagate refresh to lifecycle processor first.
    // 默認調(diào)用 DefaultLifecycleProcessor 的 onRefresh 方法
    // 找出 Lifecycle Bean 執(zhí)行 start 方法,默認情況下是沒有Lifecycle Bean的,需要自己定義
    getLifecycleProcessor().onRefresh();
    // Publish the final event.
    // 發(fā)布事件  ContextRefreshedEvent 是一個事件
    publishEvent(new ContextRefreshedEvent(this));
    // Participate in LiveBeansView MBean, if active.
    LiveBeansView.registerApplicationContext(this);
}

getLifecycleProcessor()方法獲得容器中的 LifecycleProcessor對象,默認就是 DefaultLifecycleProcessor。

LifecycleProcessor

public interface LifecycleProcessor extends Lifecycle {
	/**
	 * Notification of context refresh, e.g. for auto-starting components.
	 * 上下文刷新的通知,例如 用于自動啟動組件
	 */
	void onRefresh();
	/**
	 * Notification of context close phase, e.g. for auto-stopping components.
	 * 上下文關閉的通知,例如 用于自動停止組件。
	 */
	void onClose();
}

接口中就定義的兩個方法。onRefresh、onClose。

onRefresh

我們先來看一下 onRefresh方法的內(nèi)部邏輯,分析它是如何自動調(diào)用 start方法的。

@Override
public void onRefresh() {
    startBeans(true);
    this.running = true;
}
private void startBeans(boolean autoStartupOnly) {
    // 獲取所有的Lifecycle Bean
    Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
    // 將Lifecycle Bean 按階段分組,階段通過實現(xiàn) Phased 接口得到
    Map<Integer, LifecycleGroup> phases = new HashMap<>();
    // 遍歷所有Lifecycle Bean 按階段值進行分組
    lifecycleBeans.forEach((beanName, bean) -> {
        // 當autoStartupOnly=false,顯示調(diào)用 start()方法進行啟動,會觸發(fā)全部的Lifecycle;
        // 當autoStartupOnly=true,調(diào)用容器的 refresh 方法啟動,只會觸發(fā)isAutoStartup方法返回true的SmartLifecycle
        if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) {
            int phase = getPhase(bean);
            LifecycleGroup group = phases.get(phase);
            if (group == null) {
                group = new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly);
                phases.put(phase, group);
            }
            group.add(beanName, bean);
        }
    });
    if (!phases.isEmpty()) {
        List<Integer> keys = new ArrayList<>(phases.keySet());
        Collections.sort(keys);
        for (Integer key : keys) {
            // 調(diào)用 Lifecycle 的 start 方法
            phases.get(key).start();
        }
    }
}

這里注意一下 autoStartupOnly的值為 true。

  • autoStartupOnly=true,調(diào)用容器的 refresh 方法,由容器調(diào)用 onRefresh方法自動啟動,只會觸發(fā) isAutoStartup方法返回 trueSmartLifecycle。而 isAutoStartup屬性,小杰在分析SmartLifecycle的時候已經(jīng)講過。
  • autoStartupOnly=false,顯示調(diào)用 start()方法進行啟動,會觸發(fā)全部的Lifecycle
@Override
public void start() {
    getLifecycleProcessor().start();
    publishEvent(new ContextStartedEvent(this));
}
//傳入 false
@Override
public void start() {
    startBeans(false);
    this.running = true;
}

onClose

onClose在我沒有找到調(diào)用點,但是 onClose內(nèi)部會調(diào)用stopBeans()方法。我們直接分析stopBeans方法。

stopBeans方法跟 startBeans的邏輯大體差不多,然后調(diào)用 stop方法。

@Override
public void onClose() {
    stopBeans();
    this.running = false;
}
private void stopBeans() {
    // 獲取所有的Lifecycle Bean
    Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
    Map<Integer, LifecycleGroup> phases = new HashMap<>();
    lifecycleBeans.forEach((beanName, bean) -> {
        // 獲得 phase 的值
        int shutdownPhase = getPhase(bean);
        LifecycleGroup group = phases.get(shutdownPhase);
        // 按階段值進行分組
        if (group == null) {
            // this.timeoutPerShutdownPhase 就是等待時間
            group = new LifecycleGroup(shutdownPhase, this.timeoutPerShutdownPhase, lifecycleBeans, false);
            phases.put(shutdownPhase, group);
        }
        group.add(beanName, bean);
    });
    if (!phases.isEmpty()) {
        List<Integer> keys = new ArrayList<>(phases.keySet());
        keys.sort(Collections.reverseOrder());
        for (Integer key : keys) {
            //調(diào)用 stop 方法
            phases.get(key).stop();
        }
    }
}

stop

創(chuàng)建一個 CountDownLatch對象,如果 count不為 0 ,則線程進行等待,默認等待 30 s。

public void stop() {
  if(this.members.isEmpty()) {
    return;
  }
  if(logger.isDebugEnabled()) {
    logger.debug("Stopping beans in phase " + this.phase);
  }
  this.members.sort(Collections.reverseOrder());
  // 創(chuàng)建 CountDownLatch 對象 ,count 為 smartMemberCount
  // smartMemberCount 為 SmartLifecycle Bean的個數(shù)
  CountDownLatch latch = new CountDownLatch(this.smartMemberCount);
  Set < String > countDownBeanNames = Collections.synchronizedSet(new LinkedHashSet < > ());
  Set < String > lifecycleBeanNames = new HashSet < > (this.lifecycleBeans.keySet());
  for(LifecycleGroupMember member: this.members) {
    if(lifecycleBeanNames.contains(member.name)) {
      //調(diào)用 dostop 方法
      doStop(this.lifecycleBeans, member.name, latch, countDownBeanNames);
    } else if(member.bean instanceof SmartLifecycle) {
      // Already removed: must have been a dependent bean from another phase
      //將count值減1
      latch.countDown();
    }
  }
  try {
    //調(diào)用 await() 方法的線程會被掛起,等待一定的時間后,如果 count值還沒有為 0 才繼續(xù)執(zhí)行
    latch.await(this.timeout, TimeUnit.MILLISECONDS);
    if(latch.getCount() > 0 && !countDownBeanNames.isEmpty() && logger.isInfoEnabled()) {
      logger.info("Failed to shut down " + countDownBeanNames.size() + " bean" + (countDownBeanNames.size() > 1 ? "s" : "") + " with phase value " + this.phase + " within timeout of " + this.timeout + ": " + countDownBeanNames);
    }
  } catch(InterruptedException ex) {
    Thread.currentThread().interrupt();
  }
}
}

doStop

doStop 方法的邏輯很簡單。區(qū)分是否是SmartLifecycle類型,如果是執(zhí)行stop(Runnable callback)方法,反之執(zhí)行 stop()方法。

private void doStop(Map<String, ? extends Lifecycle> lifecycleBeans, final String beanName,
                    final CountDownLatch latch, final Set<String> countDownBeanNames) {
    Lifecycle bean = lifecycleBeans.remove(beanName);
    if (bean != null) {
        String[] dependentBeans = getBeanFactory().getDependentBeans(beanName);
        for (String dependentBean : dependentBeans) {
            doStop(lifecycleBeans, dependentBean, latch, countDownBeanNames);
        }
        try {
            // 判斷 isRunning 的值
            if (bean.isRunning()) {
                // 如果是 SmartLifecycle 類型,則執(zhí)行 stop(Runnable callback) 方法
                if (bean instanceof SmartLifecycle) {
                    if (logger.isTraceEnabled()) {
                        logger.trace("Asking bean '" + beanName + "' of type [" +
                                     bean.getClass().getName() + "] to stop");
                    }
                    countDownBeanNames.add(beanName);
                    // 這里就是為什么要調(diào)用 callback.run() 的原因
                    // 傳入的是一個 lambad 表達式,所以需要調(diào)用callback.run(),才會執(zhí)行 lambad 體
                    // 在lambad 體才會執(zhí)行 latch.countDown()
                    ((SmartLifecycle) bean).stop(() -> {
                        //將count值減1
                        latch.countDown();
                        countDownBeanNames.remove(beanName);
                        if (logger.isDebugEnabled()) {
                            logger.debug("Bean '" + beanName + "' completed its stop procedure");
                        }
                    });
                }
                else {
                    if (logger.isTraceEnabled()) {
                        logger.trace("Stopping bean '" + beanName + "' of type [" +
                                     bean.getClass().getName() + "]");
                    }
                    // 否則執(zhí)行 stop() 方法
                    bean.stop();
                    if (logger.isDebugEnabled()) {
                        logger.debug("Successfully stopped bean '" + beanName + "'");
                    }
                }
            }
            else if (bean instanceof SmartLifecycle) {
                // Don't wait for beans that aren't running...
                latch.countDown();
            }
        }
        catch (Throwable ex) {
            if (logger.isWarnEnabled()) {
                logger.warn("Failed to stop bean '" + beanName + "'", ex);
            }
        }
    }
}

關于Lifecycle的使用與源碼分析就到這啦!

到此這篇關于Spring Lifecycle的使用的文章就介紹到這了,更多相關Spring Lifecycle使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Java Socket編程簡介_動力節(jié)點Java學院整理

    Java Socket編程簡介_動力節(jié)點Java學院整理

    這篇文章主要介紹了Java Socket編程簡介的相關知識,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
    2017-05-05
  • Java?LocalDateTime獲取時間信息、格式化、轉(zhuǎn)換為數(shù)字時間戳代碼示例

    Java?LocalDateTime獲取時間信息、格式化、轉(zhuǎn)換為數(shù)字時間戳代碼示例

    其實我們在Java項目中對日期進行格式化,主要是利用一些日期格式化類,下面這篇文章主要給大家介紹了關于Java?LocalDateTime獲取時間信息、格式化、轉(zhuǎn)換為數(shù)字時間戳的相關資料,需要的朋友可以參考下
    2023-11-11
  • 一文帶你剖析Redisson分布式鎖的原理

    一文帶你剖析Redisson分布式鎖的原理

    相信使用過redis的,或者正在做分布式開發(fā)的童鞋都知道redisson組件,它的功能很多,但我們使用最頻繁的應該還是它的分布式鎖功能,少量的代碼,卻實現(xiàn)了加鎖、鎖續(xù)命(看門狗)、鎖訂閱、解鎖、鎖等待(自旋)等功能,我們來看看都是如何實現(xiàn)的
    2022-11-11
  • springboot整合vue實現(xiàn)上傳下載文件

    springboot整合vue實現(xiàn)上傳下載文件

    這篇文章主要為大家詳細介紹了springboot整合vue實現(xiàn)上傳下載文件,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-11-11
  • Java利用ElasticSearch實現(xiàn)自動補全功能

    Java利用ElasticSearch實現(xiàn)自動補全功能

    這篇文章主要為大家詳細介紹了Java如何利用ElasticSearch實現(xiàn)跟谷歌和百度類似的下拉補全提示功能,文中的示例代碼講解詳細,需要的可以參考一下
    2023-08-08
  • 使用jmx?exporter采集kafka指標示例詳解

    使用jmx?exporter采集kafka指標示例詳解

    這篇文章主要為大家介紹了使用jmx?exporter采集kafka指標示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-11-11
  • 對比Java設計模式編程中的狀態(tài)模式和策略模式

    對比Java設計模式編程中的狀態(tài)模式和策略模式

    這篇文章主要介紹了Java設計模式編程中的狀態(tài)模式和策略模式對比,文中列舉了兩種模式的相似點和不同點,并都舉了代碼的實例作為參照,需要的朋友可以參考下
    2016-04-04
  • 一文讀懂JavaWeb前后端數(shù)據(jù)交互

    一文讀懂JavaWeb前后端數(shù)據(jù)交互

    本文主要介紹了一文讀懂JavaWeb前后端數(shù)據(jù)交互,包括HTTP請求與響應、JSON數(shù)據(jù)格式以及常用的數(shù)據(jù)傳輸技術,具有一定的參考價值,感興趣的可以了解一下
    2024-01-01
  • Windows下Java環(huán)境配置的超詳細教程

    Windows下Java環(huán)境配置的超詳細教程

    這篇文章主要給大家介紹了關于Windows下Java環(huán)境配置的超詳細教程,文中通過圖文將配置的過程介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2023-01-01
  • Java中redisTemplate注入失敗NullPointerException異常問題解決

    Java中redisTemplate注入失敗NullPointerException異常問題解決

    這篇文章主要介紹了Java中redisTemplate注入失敗NullPointerException異常問題解決,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2023-08-08

最新評論

遵化市| 自治县| 潼关县| 惠水县| 兴业县| 余姚市| 确山县| 遂宁市| 安龙县| 什邡市| 河北区| 南和县| 兴山县| 田阳县| 茌平县| 水富县| 福建省| 莒南县| 隆安县| 桐城市| 武强县| 若羌县| 满城县| 黔西县| 曲松县| 陆良县| 甘孜县| 荆州市| 西丰县| 凯里市| 崇明县| 红河县| 诸暨市| 丹凤县| 嵊泗县| 乃东县| 昌图县| 崇信县| 威远县| 台湾省| 内江市|