1. 程式人生 > >spring啟動載入程式的幾種方法

spring啟動載入程式的幾種方法

轉載自:http://blog.csdn.net/lovesomnus/article/details/50158761

關於在spring  容器初始化 bean 和銷燬前所做的操作定義方式有三種:

[java] view plain copy print?
  1. import javax.annotation.PostConstruct;    
  2. import javax.annotation.PreDestroy;    
  3. publicclass DataInitializer{     
  4.     @PostConstruct
  5.     publicvoid initMethod() throws
     Exception {  
  6.         System.out.println("initMethod 被執行");  
  7.     }  
  8.     @PreDestroy
  9.     publicvoid destroyMethod() throws Exception {  
  10.         System.out.println("destroyMethod 被執行");  
  11.     }  
  12. }  

[java] view plain copy print?
  1. publicclass DataInitializer{  
  2.     publicvoid initMethod() throws Exception {  
  3.         System.out.println("initMethod 被執行");  
  4.     }  
  5.     publicvoid destroyMethod() throws Exception {  
  6.         System.out.println("destroyMethod 被執行");  
  7.     }  
  8. }  
[html] view plain copy print?
  1. <beanid="dataInitializer"class="com.somnus.demo.DataInitializer"init-method="initMethod"destory-method
    ="destroyMethod"/>

[java] view plain copy print?
  1. import org.springframework.beans.factory.DisposableBean;  
  2. publicclass DataInitializer implements InitializingBean,DisposableBean{  
  3.     @Override
  4.     publicvoid afterPropertiesSet() throws Exception {  
  5.         System.out.println("afterPropertiesSet 被執行");  
  6.     }  
  7.     @Override
  8.     publicvoid destroy() throws Exception {  
  9.         System.out.println("destroy 被執行");  
  10.     }  
  11. }  

其中第一種和第二種是同一種形式,只不過一種xml配置,另外一種採用註解形式罷了,有很大區別的是第三種,

如果同一個bean同時採用兩種方式初始化的時候執行某個方法,首先在執行順序上就會體現出來。

先執行afterPropertiesSet(),

後執行initMethod()

這裡我們看下原始碼

這方式在spring中是怎麼實現的?

通過檢視spring的載入bean的原始碼類(AbstractAutowireCapableBeanFactory)可看出其中奧妙

AbstractAutowireCapableBeanFactory類中的invokeInitMethods講解的非常清楚,原始碼如下:

[java] view plain copy print?
  1. protectedvoid invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)  
  2.       throws Throwable {  
  3.   //判斷該bean是否實現了實現了InitializingBean介面,如果實現了InitializingBean介面,則只掉呼叫bean的afterPropertiesSet方法
  4.   boolean isInitializingBean = (bean instanceof InitializingBean);  
  5.   if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {  
  6.       if (logger.isDebugEnabled()) {  
  7.           logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");  
  8.       }  
  9.       if (System.getSecurityManager() != null) {  
  10.           try {  
  11.               AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {  
  12.                   public Object run() throws Exception {  
  13.                       //直接呼叫afterPropertiesSet
  14.                       ((InitializingBean) bean).afterPropertiesSet();  
  15.                       returnnull;  
  16.                   }  
  17.               },getAccessControlContext());  
  18.           } catch (PrivilegedActionException pae) {  
  19.               throw pae.getException();  
  20.           }  
  21.       }                  
  22.       else {  
  23.           //直接呼叫afterPropertiesSet
  24.           ((InitializingBean) bean).afterPropertiesSet();  
  25.       }  
  26.   }  
  27.   if (mbd != null) {  
  28.       String initMethodName = mbd.getInitMethodName();  
  29.       //判斷是否指定了init-method方法,如果指定了init-method方法,則再呼叫制定的init-method
  30.       if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&  
  31.               !mbd.isExternallyManagedInitMethod(initMethodName)) {  
  32.               //進一步檢視該方法的原始碼,可以發現init-method方法中指定的方法是通過反射實現
  33.           invokeCustomInitMethod(beanName, bean, mbd);  
  34.       }  
  35.   }  

總結:

1:spring為bean提供了兩種初始化bean的方式,實現InitializingBean介面,實現afterPropertiesSet方法,或者在配置檔案中同過

init-method指定,兩種方式可以同時使用


2:實現InitializingBean介面是直接呼叫afterPropertiesSet方法,比通過反射呼叫init-method指定的方法效率相對來說要高點。但是

init-method方式消除了對spring的依賴


3:如果呼叫afterPropertiesSet方法時出錯,則不呼叫init-method指定的方法。

相關推薦

spring啟動載入程式方法

轉載自:http://blog.csdn.net/lovesomnus/article/details/50158761 關於在spring  容器初始化 bean 和銷燬前所做的操作定義方式有三種: [java] view plain copy p

Spring 獲取 request 的方法及其線程安全性分析

就是 base p地址 sco 便是 情況 C4D cookie tex 本文將介紹在Spring MVC開發的Web系統中,獲取request對象的幾種方法,並討論其線程安全性。 一、概述 在使用Spring MVC開發Web系統時,經常需要在處理請求時使用request

selenium中關於停止載入方法

進行頁面跳轉時,或開啟網頁時,遇到某一個資源找不到,頁面一直處於載入中,python後續程式碼無法執行, 1. 通過Python win32api鍵按下ESC中斷瀏覽器載入 具體參考selenium 自動化中斷瀏覽器載入,加快自動化與執行速度這邊文章, 相關連結: htt

Linux開機自動載入方法

linux 新增開機啟動項的三種方法。 (1)編輯檔案 /etc/rc.local 輸入命令:vim /etc/rc.local 將出現類似如下的文字片段: #!/bin/sh #This script will be executed after all the other init scripts

路由元件按需載入方法

 在Vue專案中,一般使用vue-cli構建專案後,我們會在Router資料夾下面的index.js裡面引入相關的路由元件,如: import Hello from '@/components/Hello' import Boy from '@/components/Boy

js實現延遲載入方法

js的延遲載入有助與提高頁面的載入速度,以下是延遲載入的幾種方法: 使用setTimeout延遲方法的載入時間 延遲載入js程式碼,給網頁載入留出更多時間 <script type="text/javascript" > function A(){

spring配置資料來源的方法

1.使用JNDI Spring應用程式通常部署在Java EE應用伺服器中,如WebSphere,JBoss,Tomcat這樣的Web容器。這些伺服器允許配置通過jndi獲取資料來源。 好處: (1)資料來源完全可以在應用程式之外進行管理,應用程式只需在訪

spring獲取webapplicationcontext,applicationcontext方法詳解

方法一:在初始化時儲存ApplicationContext物件 程式碼: ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml"); ac.getBean("

java-上下文以及獲取Spring的ApplicationContext的方法(整理)

起因是睡覺的時候,我在想如果被面試問道:“你知道怎麼可以獲取上下文嗎?”這個問題我感到很模糊,之前也寫過獲取上下文,但是記得好像有好幾種方法,覺得有點混淆了,所以就想自己好好整理下。 網上搜集的context上下文的幾種解釋: 一: Context上下文主要用來從上

oracle啟動/停止的方法以及 啟動和停止過程中出錯的解決辦法

一、啟動幾種方法: 1、 sqlplus /nolog connect /as sysdba startup 2、 sqlplus /nolog connect /as sysdba startup nomount alter database mount alter database o

windows下.bat程式開機自啟動方法

以下兩種方法,親測能夠執行的1、編寫VBS指令碼新建指令碼script.vbs,指令碼內容如下:set ws=WScript.CreateObject("WScript.Shell")ws.Run "C:\Users\Administrator\Desktop\aa.bat /start",0 //bat的存

SpringBoot---系統啟動載入實現的方法

1.CommandLineRunner  通過實現介面 CommandLineRunner 來實現,來完成專案啟動就載入所需要的資源。 import org.springframework.boot.CommandLineRunner; import org.springfra

SpringBoot實踐之---系統啟動載入實現的方法init、servelt、CommandLineRunner

實際應用中,我們會有在專案服務啟動的時候就去載入一些資料或做一些事情這樣的需求。 方法一:CommandLineRunner 為了解決這樣的問題,Spring Boot 為我們提供了一個方法,通過實現介面 CommandLineRunner 來實現。很簡單,只需要一個類就可以

ubuntu下圖形程式啟動方法

版權宣告:本文為本文為博主原創文章,轉載請註明出處。如有問題,歡迎指正。部落格地址:https://www.cnblogs.com/wsg1100/ @[toc] ## 0.前言 在嵌入式的場合通常會讓Linux只執行某一個特定的人機互動應用程式,本文講述了在Ubuntu環境下如何配置應用自啟動,希望對你有所

spring mvc獲取絕對路徑的方法

col 文件 結果 ret 項目 tps span ppr etc 1.首先如果是在一個controller方法中,則很簡單,直接用下面語句。 1 @RequestMapping("categoryHome") 2 public ModelAndVie

Java Spring Controller 獲取請求參數的方法

交流 str eth req turn let oca form表單 val 技術交流群:233513714 1、直接把表單的參數寫在Controller相應的方法的形參中,適用於get方式提交,不適用於post方式提交。若"Content-Type"="applic

Spring Controller 獲取請求參數的方法

不存在 orm red ID DDU usermod ping 接收 發生 1、直接把表單的參數寫在Controller相應的方法的形參中,適用於get方式提交,不適用於post方式提交。若"Content-Type"="application/x-www-form-ur

C#啟動外部程序以及等待外部程序關閉的方法

string C# main 無限 完成 nbsp text enable geb 1. 啟動外部程序,不等待其退出。 2. 啟動外部程序,等待其退出。 3. 啟動外部程序,無限等待其退出。 4. 啟動外部程序,通過事件監視其退出。 // using Sy

windows下.bat程序開機自啟動方法

win 命名 set 路徑 ima 窗口 ros 自啟動 obj 以下兩種方法,親測能夠執行的1、編寫VBS腳本新建腳本script.vbs,腳本內容如下:set ws=WScript.CreateObject("WScript.Shell")ws.Ru

Linux獲取網頁原始碼的方法 linux爬蟲程式

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow 也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!