SpringBean中怎么實現(xiàn)初始化-創(chuàng)新互聯(lián)

SpringBean中怎么實現(xiàn)初始化,針對這個問題,這篇文章詳細介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

網(wǎng)站建設(shè)哪家好,找創(chuàng)新互聯(lián)!專注于網(wǎng)頁設(shè)計、網(wǎng)站建設(shè)、微信開發(fā)、小程序制作、集團企業(yè)網(wǎng)站建設(shè)等服務(wù)項目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了肅南裕固族自治免費建站歡迎大家使用!

一、前言

日常開發(fā)過程有時需要在應(yīng)用啟動之后加載某些資源,或者在應(yīng)用關(guān)閉之前釋放資源。Spring 框架提供相關(guān)功能,圍繞 Spring Bean 生命周期,可以在 Bean 創(chuàng)建過程初始化資源,以及銷毀 Bean 過程釋放資源。Spring 提供多種不同的方式初始化/銷毀 Bean,如果同時使用這幾種方式,Spring 如何處理這幾者之間的順序?

二、姿勢剖析

首先我們先來回顧一下 Spring 初始化/銷毀 Bean 幾種方式,分別為:

init-method/destroy-method  InitializingBean/DisposableBean  @PostConstruct/@PreDestroy  ContextStartedEvent/ContextClosedEvent

PS: 其實還有一種方式,就是繼承 Spring Lifecycle 接口。不過這種方式比較繁瑣,這里就不再分析。

2.1、init-method/destroy-method

這種方式在配置文件文件指定初始化/銷毀方法。XML 配置如下

<bean id="demoService" class="com.dubbo.example.provider.DemoServiceImpl" destroy-method="close" init-method="initMethod"/>

或者也可以使用注解方式配置:

@Configurablepublic class AppConfig {  @Bean(initMethod = "init", destroyMethod = "destroy")  public HelloService hello() {    return new HelloService();  }}

還記得剛開始接觸學(xué)習(xí) Spring 框架,使用就是這種方式。

2.2、InitializingBean/DisposableBean

這種方式需要繼承 Spring 接口 InitializingBean/DisposableBean,其中 InitializingBean 用于初始化動作,而 DisposableBean 用于銷毀之前清理動作。使用方式如下:

@Servicepublic class HelloService implements InitializingBean, DisposableBean {    @Override  public void destroy() throws Exception {    System.out.println("hello destroy...");  }  @Override  public void afterPropertiesSet() throws Exception {    System.out.println("hello init....");  }}

2.3、@PostConstruct/@PreDestroy

這種方式相對于上面兩種方式來說,使用方式最簡單,只需要在相應(yīng)的方法上使用注解即可。使用方式如下:

@Servicepublic class HelloService {  @PostConstruct  public void init() {    System.out.println("hello @PostConstruct");  }  @PreDestroy  public void PreDestroy() {    System.out.println("hello @PreDestroy");  }}

這里踩過一個坑,如果使用 JDK9 之后版本 ,@PostConstruct/@PreDestroy 需要使用 maven 單獨引入 javax.annotation-api,否者注解不會生效。

2.4、ContextStartedEvent/ContextClosedEvent

這種方式使用 Spring 事件機制,日常業(yè)務(wù)開發(fā)比較少見,常用與框架集成中。Spring 啟動之后將會發(fā)送 ContextStartedEvent 事件,而關(guān)閉之前將會發(fā)送 ContextClosedEvent 事件。我們需要繼承 Spring ApplicationListener 才能監(jiān)聽以上兩種事件。

@Servicepublic class HelloListener implements ApplicationListener {  @Override  public void onApplicationEvent(ApplicationEvent event) {    if(event instanceof ContextClosedEvent){      System.out.println("hello ContextClosedEvent");    }else if(event instanceof ContextStartedEvent){      System.out.println("hello ContextStartedEvent");    }  }}

也可以使用 @EventListener注解,使用方式如下:

public class HelloListenerV2 {    @EventListener(value = {ContextClosedEvent.class, ContextStartedEvent.class})  public void receiveEvents(ApplicationEvent event) {    if (event instanceof ContextClosedEvent) {      System.out.println("hello ContextClosedEvent");    } else if (event instanceof ContextStartedEvent) {      System.out.println("hello ContextStartedEvent");    }  }}

PS:只有調(diào)用 ApplicationContext#start 才會發(fā)送 ContextStartedEvent。若不想這么麻煩,可以監(jiān)聽 ContextRefreshedEvent 事件代替。一旦 Spring 容器初始化完成,就會發(fā)送 ContextRefreshedEvent。

三、綜合使用

回顧完上面幾種方式,這里我們綜合使用上面的四種方式,來看下 Spring 內(nèi)部的處理順序。在看結(jié)果之前,各位讀者大人可以猜測下這幾種方式的執(zhí)行順序。

public class HelloService implements InitializingBean, DisposableBean {  @PostConstruct  public void init() {    System.out.println("hello @PostConstruct");  }  @PreDestroy  public void PreDestroy() {    System.out.println("hello @PreDestroy");  }  @Override  public void destroy() throws Exception {    System.out.println("bye DisposableBean...");  }  @Override  public void afterPropertiesSet() throws Exception {    System.out.println("hello InitializingBean....");  }  public void xmlinit(){    System.out.println("hello xml-init...");  }  public void xmlDestory(){    System.out.println("bye xmlDestory...");  }  @EventListener(value = {ContextClosedEvent.class, ContextStartedEvent.class})  public void receiveEvents(ApplicationEvent event) {    if (event instanceof ContextClosedEvent) {      System.out.println("bye ContextClosedEvent");    } else if (event instanceof ContextStartedEvent) {      System.out.println("hello ContextStartedEvent");    }  }}

xml 配置方式如下:

<context:annotation-config />  <context:component-scan base-package="com.dubbo.example.demo"/>    <bean class="com.dubbo.example.demo.HelloService" init-method="xmlinit" destroy-method="xmlDestory"/>

應(yīng)用啟動方法如下:

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/dubbo-provider.xml");context.start();context.close();

程序輸出結(jié)果如下所示:

最后采用圖示說明總結(jié)以上結(jié)果:

四、源碼解析

不知道各位讀者有沒有猜對這幾種方式的執(zhí)行順序,下面我們就從源碼角度解析 Spring 內(nèi)部處理的順序。

4.1、初始化過程

使用 ClassPathXmlApplicationContext 啟動 Spring 容器,將會調(diào)用 refresh 方法初始化容器。初始化過程將會創(chuàng)建 Bean 。最后當(dāng)一切準備完畢,將會發(fā)送 ContextRefreshedEvent。當(dāng)容器初始化完畢,調(diào)用 context.start() 就發(fā)送 ContextStartedEvent 事件。

refresh 方法源碼如下:

public void refresh() throws BeansException, IllegalStateException {  synchronized (this.startupShutdownMonitor) {      //... 忽略無關(guān)代碼      // 初始化所有非延遲初始化的 Bean      finishBeanFactoryInitialization(beanFactory);      // 發(fā)送 ContextRefreshedEvent      finishRefresh();      //... 忽略無關(guān)代碼  }}

一路跟蹤 finishBeanFactoryInitialization 源碼,直到 AbstractAutowireCapableBeanFactory#initializeBean,源碼如下:

protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {  Object wrappedBean = bean;  if (mbd == null || !mbd.isSynthetic()) {    // 調(diào)用 BeanPostProcessor#postProcessBeforeInitialization 方法    wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);  }  try {    // 初始化 Bean    invokeInitMethods(beanName, wrappedBean, mbd);  }  catch (Throwable ex) {    throw new BeanCreationException(        (mbd != null ? mbd.getResourceDescription() : null),        beanName, "Invocation of init method failed", ex);  }}

BeanPostProcessor 將會起著攔截器的作用,一旦 Bean 符合條件,將會執(zhí)行一些處理。這里帶有 @PostConstruct 注解的 Bean 都將會被 CommonAnnotationBeanPostProcessor 類攔截,內(nèi)部將會觸發(fā) @PostConstruct 標(biāo)注的方法。

接著執(zhí)行 invokeInitMethods ,方法如下:

protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)    throws Throwable {  boolean isInitializingBean = (bean instanceof InitializingBean);  if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {    // 省略無關(guān)代碼    // 如果是 Bean 繼承 InitializingBean,將會執(zhí)行 afterPropertiesSet 方法    ((InitializingBean) bean).afterPropertiesSet();  }  if (mbd != null) {    String initMethodName = mbd.getInitMethodName();    if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&        !mbd.isExternallyManagedInitMethod(initMethodName)) {      // 執(zhí)行 XML 定義 init-method      invokeCustomInitMethod(beanName, bean, mbd);    }  }}

如果 Bean 繼承 InitializingBean 接口,將會執(zhí)行 afterPropertiesSet 方法,另外如果在 XML 中指定了 init-method ,也將會觸發(fā)。

上面源碼其實都是圍繞著 Bean 創(chuàng)建的過程,當(dāng)所有 Bean 創(chuàng)建完成之后,調(diào)用 context#start 將會發(fā)送 ContextStartedEvent 。這里源碼比較簡單,如下:

public void start() {  getLifecycleProcessor().start();  publishEvent(new ContextStartedEvent(this));}

4.2、銷毀過程

調(diào)用 ClassPathXmlApplicationContext#close 方法將會關(guān)閉容器,具體邏輯將會在 doClose 方法執(zhí)行。

doClose 這個方法首先發(fā)送 ContextClosedEvent,然再后開始銷毀 Bean。

靈魂拷問:如果我們顛倒上面兩者順序,結(jié)果會一樣嗎?

doClose 源碼如下:

protected void doClose() {  if (this.active.get() && this.closed.compareAndSet(false, true)) {    // 省略無關(guān)代碼    try {      // Publish shutdown event.      publishEvent(new ContextClosedEvent(this));    }    catch (Throwable ex) {      logger.warn("Exception thrown from ApplicationListener handling ContextClosedEvent", ex);    }    // 銷毀 Bean    destroyBeans();    // 省略無關(guān)代碼  }}

destroyBeans 最終將會執(zhí)行 DisposableBeanAdapter#destroy,@PreDestroy、DisposableBean、destroy-method 三者定義的方法都將會在內(nèi)部被執(zhí)行。

首先執(zhí)行 DestructionAwareBeanPostProcessor#postProcessBeforeDestruction,這里方法類似與上面 BeanPostProcessor。

@PreDestroy 注解將會被 CommonAnnotationBeanPostProcessor 攔截,這里類同時也繼承了 DestructionAwareBeanPostProcessor。

最后如果 Bean 為 DisposableBean 的子類,將會執(zhí)行 destroy 方法,如果在 xml 定義了 destroy-method 方法,該方法也會被執(zhí)行。

public void destroy() {  if (!CollectionUtils.isEmpty(this.beanPostProcessors)) {    for (DestructionAwareBeanPostProcessor processor : this.beanPostProcessors) {      processor.postProcessBeforeDestruction(this.bean, this.beanName);    }  }  if (this.invokeDisposableBean) {    // 省略無關(guān)代碼    // 如果 Bean 繼承 DisposableBean,執(zhí)行 destroy 方法    ((DisposableBean) bean).destroy();      }  if (this.destroyMethod != null) {    // 執(zhí)行 xml 指定的 destroy-method 方法    invokeCustomDestroyMethod(this.destroyMethod);  }  else if (this.destroyMethodName != null) {    Method methodToCall = determineDestroyMethod();    if (methodToCall != null) {      invokeCustomDestroyMethod(methodToCall);    }  }}

五、總結(jié)

init-method/destroy-method 這種方式需要使用 XML 配置文件或單獨注解配置類,相對來說比較繁瑣。而InitializingBean/DisposableBean 這種方式需要單獨繼承 Spring 的接口實現(xiàn)相關(guān)方法。@PostConstruct/@PreDestroy 這種注解方式使用方式簡單,代碼清晰,比較推薦使用這種方式。

另外 ContextStartedEvent/ContextClosedEvent 這種方式比較適合在一些集成框架使用,比如 Dubbo 2.6.X 優(yōu)雅停機就是用改機制。

關(guān)于SpringBean中怎么實現(xiàn)初始化問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識。

網(wǎng)站題目:SpringBean中怎么實現(xiàn)初始化-創(chuàng)新互聯(lián)
本文鏈接:http://www.muchs.cn/article12/depedc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站內(nèi)鏈、品牌網(wǎng)站建設(shè)、企業(yè)建站、網(wǎng)站導(dǎo)航手機網(wǎng)站建設(shè)、定制開發(fā)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站建設(shè)網(wǎng)站維護公司