2013-11-01 33 views
0

我現在正在研究Opendaylight項目(一個由思科領導的開源SDN控制器項目),並發現該項目使用apache.felix.dm包中的資源動態管理equinox(OSGi框架)上的服務依賴項,在運行期間。apache.felix.dm包中的init()和start()方法有什麼區別?

爲了理解dm的機制,我已經跟蹤了apache.felix.dm包下的ComponentImpl.java中的代碼。我現在理解的是:

  1. DependencyManager將在滿足所有服務依賴關係後調用init()方法。
  2. start()方法將在init()方法後但在該類提供的服務正在OSGi框架中註冊之前調用。

寫入代碼調用機構(它們都位於ComponentImpl.java)提供如下:

的方法調用的init():

private void activateService(State state) { 
    String init; 
    synchronized (this) { 
     init = m_callbackInit; 
    } 
    // service activation logic, first we initialize the service instance itself 
    // meaning it is created if necessary and the bundle context is set 
    initService(); 
    // now is the time to configure the service, meaning all required 
    // dependencies will be set and any callbacks called 
    configureService(state); 
    // flag that our instance has been created 
    m_isInstantiated = true; 
    // then we invoke the init callback so the service can further initialize 
    // itself 
    invoke(init); 
    // see if any of this caused further state changes 
    calculateStateChanges(); 
} 

的方法來調用啓動():

private void bindService(State state) { 
    String start; 
    synchronized (this) { 
     start = m_callbackStart; 
    } 

    // configure service with extra-dependencies which might have been added from init() method. 
    configureServiceWithExtraDependencies(state); 
    // inform the state listeners we're starting 
    stateListenersStarting(); 
    // invoke the start callback, since we're now ready to be used 
    invoke(start); 
    // start tracking optional services 
    startTrackingOptional(state); 
    // register the service in the framework's service registry 
    registerService(); 
    // inform the state listeners we've started 
    stateListenersStarted(); 
} 

現在我的問題是:什麼是()初始化之間的差異,start()方法?既然在服務註冊到OSGi框架之前它們都被調用,爲什麼它們需要分離? Thx對於任何想法,請告訴我,如果我的理解是不正確的。

此致

周杰倫

+0

按照init的概念將它加載到類中,在調用完成後準備就緒,開始撥打電話 –

+0

請原諒我,您能否更詳細地解釋您提到的「調用」?這就像「回撥」功能嗎? –

回答

0

其原因既具有initstart方法如下。依賴管理器允許你以(Java)代碼聲明性地定義組件及其依賴關係。這可以在啓動捆綁包時完成,但有時組件可能具有依賴於某個配置或其某個依賴項的依賴項。換句話說,您可能在運行時想要添加到組件的依賴關係。

在這種情況下,您可以做的是在您的組件實現中定義一個init(Component c)方法。在你的組件被初始化並且所有必需的依賴被注入(或者它們的回調被調用)之後,這個方法將被調用。所以在這一點上,你有機會獲得這種依賴在你的組件,你可以決定的基礎上,通過這種依賴所獲得的信息,動態地添加另一種成分,如:

public volatile OtherService s; // an injected service dependency 

public void init(Component c) { 
    if (s.needsSomeService()) { 
    DependencyManager dm = c.getDependencyManager(); 
    c.add(dm.createServiceDependency() 
     .setService(SomeService.class) 
     .setInstanceBound(true) 
     .setRequired(true)); 
    } 
} 

一旦SomeService可用時,start()方法將被調用並且您的組件可用(意味着它是否發佈服務,現在就可以完成)。

簡而言之:init方法的存在允許您操作您自己的組件定義並在運行時動態添加額外的依賴關係。然後調用start方法一次全部依賴關係可用。

在簡單的情況下,你沒有這樣的要求,使用任何方法來做你的初始化是好的。

+0

Thx爲您提供的詳細信息! –

相關問題