<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    隨筆 - 1  文章 - 37  trackbacks - 0
    <2025年5月>
    27282930123
    45678910
    11121314151617
    18192021222324
    25262728293031
    1234567

    留言簿(16)

    隨筆分類

    隨筆檔案

    文章分類

    文章檔案

    test

    搜索

    •  

    最新評論

    Spring Dynamic Modules Reference Guide

    for OSGi(tm) Service Platforms.

    Version 1.0 M3


    1.0 Introduction

    This document is the reference guide for Spring Dynamic Modules. It defines the syntax and semantics for the OSGi Service Platform based namespaces; the Dynamic Modules extender bundle; and the OSGi manifest header entries defined by Dynamic Modules. For a tutorial introduction to building OSGi-based applications with Spring Dynamic Modules see the online tutorials and user guide.

    OSGi developers looking for an introduction to Spring should review the introductory articles on the springframework.org site.

    Note: OSGi is a trademark of the OSGi Alliance. Project name is pending final approval from the Alliance.

    Note: Please see the known issues page for Spring Dynamic Modules 1.0 M3 release.

    由于商標關系,Spring-osgi改名為 Spring Dynamic Modules


    這個文檔是Spring Dynamic Modules的手冊。它定義了基于名字空間的OSGI服務平臺的語法和語義,動態模塊bundle和由動態模塊定義的OSGI manifest header entries。通過在線指南和用戶指南可以了解到使用Spring Dynamic Modules構造基于OSGI的應用

    Why Spring Dynamic Modules?

    The Spring Framework is the leading full-stack Java/JEE application framework. It provides a lightweight container and a non-invasive programming model enabled by the use of dependency injection, AOP, and portable service abstractions. The OSGi Service Platform offers a dynamic application execution environment in which modules (bundles) can be installed, updated, or removed on the fly. It also has excellent support for modularity and versioning.

    Spring是一個全功能的Java/JEE應用框架。它提供了一個輕量級的容易和一個用于依賴注入的非侵入式編程模塊,AOP功能和便攜式服務抽取。OSGI服務平臺提供了一個動態應用執行環境,模塊能隨時被加載,更新或卸載。當然它對模塊和版本控制有很好的支持。

    Spring Dynamic Modules makes it easy to write Spring applications that can be deployed in an OSGi execution environment, and that can take advantage of the services offered by the OSGi framework. Spring's OSGi support also makes development of OSGi applications simpler and more productive by building on the ease-of-use and power of the Spring Framework. For enterprise applications, the combination of Spring Dynamic Modules and the OSGi platform provides:

    • Better separation of application logic into modules, with runtime enforcement of module boundaries
    • The ability to deploy multiple versions of a module (or library) concurrently
    • The ability to dynamically discover and use services provided by other modules in the system
    • The ability to dynamically install, update and uninstall modules in a running system
    • Use of the Spring Framework to instantiate, configure, assemble, and decorate components within and across modules.
    • A simple and familiar programming model for enterprise developers to exploit the features of the OSGi platform.

    We believe that the combination of OSGi and Spring offers a comprehensive model for building enterprise applications.\

    Spring Dynamic Modules使編寫一個部署在OSGI執行環境中的Spring應用變得簡單,它能利用OSGI框架提供的服務。Spring的osgi支持也使構建在Spring框架中的OSGI應用開發變得更簡單,更高產。對于企業級應用,Spring動態模塊與OSGI平臺的整合能提供以下功能:

    • 模塊內部更好的應用邏輯分離
    • 同時部署同一模塊的多個版本
    • 在系統中動態發現和使用模塊提供的服務
    • 在系統運行時動態安裝,更新和卸載模塊
    • 使用Spring框架初始化,配置,整合并使用模塊中和跨模塊的組件
    • 對于使用OSGI平臺特性的企業級開發者來說這些都是簡單和熟悉的編程模型

    Supported OSGi and JDK versions

    Spring Dynamic Modules supports OSGi R4 and above, and JDK level 1.4 and above. Bundles deployed for use with Spring Dynamic Modules should specify "Bundle-ManifestVersion: 2" in their manifest. We test against Equinox, Felix, and Knopflerfish as part of our continuous integration process.


    要使用Spring動態模塊應該在MANIFEST.MF中指定 Bundle-ManifestVersion: 2

    Structure of this document

    Chapter 2, "Bundles and Application Contexts" describes the relationship between an OSGi Bundle and a Spring Application Context, and introduces the Spring Extender Bundle support for instantiating application contexts automatically.

    第二章,"Bundles and Application Contexts"描述了OSGI Bundle與Spring Application Context 的關系,并且介紹了Spring Extender Bundle支持自動初始化應用上下文Application Contexts

    Chapter 3, "Packaging and Deploying Spring-based OSGi applications" describes how to deploy the Spring Framework jar files in an OSGi environment, and how to reference external APIs from your application bundles should you need to do so. This chapter also explains some of the issues to be aware of when using existing enterprise libraries not designed for OSGi in an OSGi environment.

    第三章,"Packaging and Deploying Spring-based OSGi applications" 描述了如何將Spring框架的jar文件部署到OSGI環境中,并且如何在你的應用bundles中引用外部APIs。本章還解釋了在OSGI環境中當使用一些并不是為OSGI而設計的已經存在的企業類庫時出現的問題

    Chapter 4, "The Service Registry" describes how to export Spring beans as services in the OSGi service registry, and how to inject references to OSGi services into beans. This chapter also defines how the dynamic life-cycle of OSGi services and bundles is supported.

    第四章,"The Service Registry" 描述了如何在OSGi service registry中將Spring beans做為服務輸出,如何將OSGI服務引用注入到bean里。本章還定義了如何動態支持OSGI服務和Bundles的生命周期

    Chapter 5, "Working with Bundles" describes how to declare a bean that represents an OSGi bundle, including support for installing new bundles into the OSGi platform.

    第五章,"Working with Bundles"? 描述了如何聲明一個bean,表現為一個OSGI bundle,包括對安裝一個新bundle到OSGI平臺中的支持。

    Chapter 6, "Compendium Services" describes the support provided for the OSGi Compendium Services, including the Configuration Admin service.

    第六章,"Compendium Services" 描述了OSGi Compendium Services提供的支持,包括Configuration Admin service

    Chapter 7, "Testing OSGi based Applications" explains the integration testing support provided by Spring Dynamic Modules. This support enables you to write simple JUnit integration tests that can start up an OSGi environment, install the bundles needed for the integration test, execute the test case(s) inside of OSGi, and return the results to the runner. This support makes it easy to integrate OSGi integration testing into any environment that can work with JUnit.

    第七章,"Testing OSGi based Applications" 介紹了Spring動態模塊提供的綜合測試支持。這個功能使你能寫一些簡單的JUnit綜合測試,這個功能能啟動OSGI環境,安裝測試所需的bundles,執行OSGI里的測試案例,并且返回結果。這個功能使 將OSGI綜合測試整合進任何JUnit環境 變得簡單。

    Appendix A, "Extensions" describes extensions that are included in the 1.0 distribution, but are not guaranteed to be maintained in a backward-compatible form in future point releases. We anticipate these features moving into the core specification over time.


    Appendix B, "Roadmap" describes some features that are included in the 1.0 distribution but are still considered early-access. The externals of these features may change in future releases. This appendix also discusses other planned features for which no implementation yet exists.

    Appendix C defines the schemas provided by Spring Dynamic Modules.


    2.0 Bundles and Application Contexts

    The unit of deployment (and modularity) in OSGi is the bundle (see section 3.2 of the OSGi Service Platform Core Specification). A bundle known to the OSGi runtime is in one of three steady states: installed, resolved, or active. Bundles may export services (objects) to the OSGi service registry, and by so doing make these services available for other bundles to discover and to use. Bundles may also export Java packages, enabling other bundles to import the exported types.

    OSGI中的一個部署(或模塊)單元稱為bundle。一個OSGI運行環境中的bundle有3個固定的狀態:installed,resolved, active。這些bundle能做為服務輸出到OSGi service registry,這樣這些服務就能被其他bundle發現和使用。bundle也可以輸出為java包,使其他bundle能夠引用這些被輸出的類型。

    In Spring the primary unit of modularity is an application context, which contains some number of beans (objects managed by the Spring application context). Application contexts can be configured in a hierarchy such that a child application context can see beans defined in a parent, but not vice-versa. The Spring concepts of exporters and factory beans are used to export references to beans to clients outside of the application context, and to inject references to services that are defined outside of the application context.

    Spring中最主要的模塊單元是application context,它包含了一定數量的bean(由spring application context管理)。Application contexts可以被配置成父子層次,例如child application 能找到parent application 中定義的bean,反之則不行。Spring中的exporters和factory beans的是將bean引用輸出到application context以外的客戶端,并且將這些引用注入客戶端定義的服務中。

    There is a natural affinity between an OSGi bundle and a Spring application context. Using Spring Dynamic Modules, an active bundle may contain a Spring application context, responsible for the instantiation, configuration, assembly, and decoration of the objects (beans) within the bundle. Some of these beans may optionally be exported as OSGi services and thus made available to other bundles, beans within the bundle may also be transparently injected with references to OSGi services.

    OSGi bundle和Spring application context是天生的一對(natural affinity)。如果使用了Spring Dynamic Modules(Spring-osgi),那么一個狀態為active的bundle也許包含一個spring application context,它負責bundle中的bean的初始化,配置,整合和裝載。

    2.1 The Spring Dynamic Modules Extender bundle

    Spring Dynamic Modules provides an OSGi bundle org.springframework.osgi.spring-osgi-extender. This bundle is responsible for instantiating the Spring application contexts for your application bundles. It serves the same purpose as the ContextLoaderListener does for Spring web applications. Once the extender bundle is installed and started it looks for any existing Spring-powered bundles that are already in the ACTIVE state and creates application contexts on their behalf. In addition, it listens for bundle starting events and automatically creates an application context for any Spring-powered bundle that is subsequently started. Section 3 describes what the extender recognizes as a "Spring-powered bundle".

    Spring Dynamic Modules提供了一個OSGi bundle - org.springframework.osgi.spring-osgi-extender。這個bundle負責為你的application bundles初始化一個Spring application contexts。它的功能與Spring web applications中的ContextLoaderListener一樣。一旦這個bundle(org.springframework.osgi.spring-osgi-extender)被安裝并且啟動,它將查找所有已經存在的具有spring-powered的狀態為ACTIVE的bundle,然后為它們創建一個application context。另外,它還監聽bundle的啟動事件并自動為這個隨后啟動的bundle創建一個appliation context。第3節描述了什么樣的bundle具備Spring-powered。

    2.2 Application Context Creation

    The extender bundle creates applications contexts asynchronously. This behavior ensures that starting an OSGi Service Platform is fast and that bundles with service inter-dependencies do not cause deadlock on startup. A Spring-powered bundle may therefore transition to the STARTED state before its application context has been created. It is possible to force synchronous creation of application contexts on a bundle-by-bundle basis. See section 3 for information on how to specify this behavior.

    Spring的extender bundle (org.springframework.osgi.spring-osgi-extender)生成applications contexts是異步過程,不會使bundle間的相互依賴發生死鎖而減緩OSGI服務平臺的速度,因此一個具有Spring-powered的bundle的狀態可能會在extender bundle為它生成生成application context之前就轉變成STARTED。也可以強行一個bundle一個bundle的同步創建application contexts,第三節詳細介紹了這個過程。

    If application context creation fails for any reason then the failure cause is logged. The bundle remains in the STARTED state. There will be no services exported to the registry from the application context in this scenario.

    任何一個application context創建失敗都會被記錄,bundle的狀態繼續保持為STARTED,并且這個bundle不會有任何服務被注冊。

    2.2.1 Mandatory Service Dependencies

    If an application context declares mandatory dependencies on the availability of certain OSGi services (see section 4.0) then creation of the application context is blocked until all mandatory dependencies can be satisfied through matching services available in the OSGi service registry. Since a service may come and go at any moment in an OSGi environment, this behavior only guarantees that all mandatory services were available at the moment creation of the application context began. One or more services may subsequently become unavailable again during the process of application context creation. Section 4.0 describes what happens when a mandatory service reference becomes unsatisfied. In practice for most enterprise applications built using Spring Dynamic Modules services the set of available services and bundles will reach a steady state once the platform and its installed bundles are all started. In such a world the behavior of waiting for mandatory dependencies simply ensures that bundles A and B, where bundle A depends on services exported by bundle B, may be started in any order.

    如果一個application context聲明有強制依賴某個有效的OSGI服務,那么這個application context的線程將會暫時阻塞直到所有的強制依賴服務都與OSGi service registry中的服務相匹配。因為一個服務隨時可能出現,所以這個阻塞過程僅僅能保證所有的強制依賴在application context生成時可用,而application context創建后某些服務可能會重新變得不可用。第四節描述了當一個強制依賴服務引用不匹配時會發生什么。在大多數用Spring Dynamic Modules構建服務的企業級應用實踐中,一旦OSGI平臺和它的已安裝的bundle被啟動后,這些服務和bundle就會達到一個穩定的狀態。

    A timeout applies to the wait for mandatory dependencies to be satisfied. By default the timeout is set to 5 minutes, but this value can be configured using the timeout directive. See section 3.0 for details.

    超時用于等待強制依賴關系被解除,默認的超時時間是5分鐘,但是可以通過配置修改這個值。具體細節參見3.0節

    It is possible to change the application context creation semantics so that application context creation fails if all mandatory services are not immediately available upon startup (see section 3.1). When configured to not wait for dependencies, a bundle with unsatisfied mandatory dependencies will be stopped, leaving the bundle in the RESOLVED state.

    如果系統啟動時所有的依賴服務不能馬上可用,可以修改application context的創建邏輯使application context創建失敗。當帶有強制依賴的bundle配置成不等待依賴服務時,它將被停止,狀態標記為RESOLVED。

    2.2.2 Application Context Service Publication

    Once the application context creation for a bundle has completed, the application context object is automatically exported as a service available through the OSGi Service Registry. The context is published under the interface org.springframework.context.ApplicationContext (and also all of the visible super-interfaces and types implemented by the context). The published service has a service property named org.springframework.context.service.name whose value is set to the bundle symbolic name of the bundle hosting the application context. It is possible to prevent publication of the application context as a service using a directive in the bundle's manifest. See section 3.2 for details.

    一旦bundle的application context創建完成,application context對象將通過OSGi Service Registry注冊為服務,發布類型為org.springframework.context.ApplicationContext,它會包含一個屬性org.springframework.context.service.name,值為它的bundle的標記名(symbolic name)。可以通過配置bundle的MANIFEST.MF使application context不做為一個服務發布。

    Note: the application context is published as a service primarily to facilitate testing, administration, and management. Accessing this context object at runtime and invoking getBean() or similar operations is discouraged. The preferred way to access a bean defined in another application context is to export that bean as an OSGi service from the defining context, and then to import a reference to that service in the context that needs access to the service. Going via the service registry in this way ensures that a bean only sees services with compatible versions of service types, and that OSGi platform dynamics are respected.


    注意:application context發布為服務主要是為了方便測試,管理和操作。不鼓勵運行時訪問context對象和通過getBean()之類的方法。要訪問一個定義在別的application context中的bean,更好的方法是在那個application context中將bean輸出為OSGi服務,然后在需要訪問這個服務的application context中引入服務的引用,通過服務注冊,可以確保一個bean只能看見與之版本兼容的服務類型,這也是OSGi動態平臺所注重的地方。

    2.3 Bundle Lifecycle

    OSGi is a dynamic platform: bundles may be installed, started, updated, stopped, and uninstalled at any time during the running of the framework.

    OSGi是一個動態平臺:運行中的OSGi框架可以在任何時候安裝,啟動,更新,停止和卸載bundle。

    When an active bundle is stopped, any services it exported during its lifetime are automatically unregistered and the bundle returns to the resolved state. A stopped bundle should release any resources it has acquired and terminate any threads. Packages exported by a stopped bundle continue to be available to other bundles.

    當一個活動的bundle被停止時,在它處于激活狀態時輸出的任何服務將自動卸載,并且它的狀態會返回到RESOLVED。一個停止活動的bundle應該釋放它所有獲得的資源并終止所有它開啟的線程。但是它輸出的packages仍然對其他bundles有效。

    A bundle in the resolved state may be uninstalled: packages that were exported by an uninstalled bundle continue to be available to bundles that imported them (but not to newly installed bundles).

    一個狀態為RESOLVED的bundle可以被卸載:一個被卸載的bundle輸出的packages對其他已經存在的bundles仍然有效(但是對新安裝的bundles無效)。

    A bundle in the resolved state may also be updated. The update process migrates from one version of a bundle to another version of the same bundle.

    一個狀態為RESOLVED的bundle也可以被更新。這個更新過程是指同一個bundle從一個版本移植到另一個版本。


    Finally of course a resolved bundle can be started, which transitions it to the active state.

    最后一個狀態為RESOLVED的bundle還可以被啟動,它的狀態則改變為ACTIVE。

    The OSGi PackageAdminrefreshPackages operation refreshes packages across the whole OSGi framework or a given subset of installed bundles. During the refresh, an application context in an affected bundle will be stopped and restarted. After a refreshPackages operation, packages exported by older versions of updated bundles, or packages exported by uninstalled bundles, are no longer available. Consult the OSGi specifications for full details.

    OSGi中的org.osgi.service.packageadmin.PackageAdmin.refreshPackages(Bundle[] bundles)可以刷新整個OSGi框架或指定的一列已安裝的bundles中的packages。如果某個bundle被刷新,那么它的application context將會被停止然后刷新。refreshPackages方法執行完畢后,被更新的舊版本的或被卸載了的bundle的packages將不再有效。具體細節參見OSGi規范。

    When a Spring-powered bundle is stopped, the application context created for it is automatically destroyed. All services exported by the bundle will be unregistered (removed from the service registry) and the normal application context tear-down life-cycle is observed (DisposableBean and destroy-method callbacks are invoked on beans in the context).


    當一個具有Spring-powered的bundle被停止時,它的application context將自動銷毀,它輸出的服務將被注銷(從service registry刪除),然后application context生命周期的正常注銷將開始執行(回調context中所有bean的destroy-method

    If a Spring-powered bundle that has been stopped is subsequently re-started, a new application context will be created for it.

    如果一個已經停止的具有Spring-powered的bundle后來又重新啟動,那么一個新的application context將會被創建。

    2.4 The Resource abstraction

    The Spring Framework defines a resource abstraction for loading resources within an application context (see ). All resource loading is done through the ResourceLoader associated with the application context. The ResourceLoader is also available to beans wishing to load resources programmatically. Resource paths with explicit prefixes - for example "classpath:" are treated uniformly across all application context types (for example, web application contexts and classpath-based application contexts). Relative resource paths are interpreted differently based on the kind of application context being created. This enables easy integration testing outside of the ultimate deployment environment.

    Spring框架為從application context中加載資源定義了一個資源提取功能。通過與application context相關聯的ResourceLoader可以完成資源加載。ResourceLoader也適用于bean在程序中加載資源。資源路徑會有很清楚的前綴 - 例如“classpath:”前綴將一律被看成是跨application context級的類型(例如web application contexts和基于classpath的application contexts)。其他相關的資源路徑則根據application context的創建方式不同而不同,這使得最終部署環境的外部綜合測試變得簡單。

    The Spring extender bundles creates a special subclass of application context, an OSGiApplicationContext. An OSGi application context treats a relative resource path as a reference to a resource defined within the bundle (the bundle and its attached fragments will be searched for matching resources). The context also supports the explicit resource path prefixes osgibundle and osgibundlejar.

    The Spring extender bundles會創建一個特殊的application context的子application context - OSGiApplicationContext(只適用于OSGi環境的application context)。一個OSGi application context將相關的資源路徑看成定義在bundle中的資源引用(在bundle和它的附加文件中查找匹配的資源)。這個OSGi application context也支持前綴為 "osgibundle:" 和 "osgibundlejar:" 的資源路徑。

    A resource path of the format "osgibundle:x/y/z" searches for resource "x/y/z" in the bundle and its attached fragments (this is the same as the relative resource behavior).

    一個格式為"osgibundle:x/y/z"的資源路徑表示在bundle和它的附加文件中查找資源"x/y/z"(這與其它的查找方式是相似的)。

    A resource path of the format "osgibundlejar:x/y/z" searches for resource "x/y/z" in the bundle only, ignoring any attached fragments.

    一個格式為"osgibundlejar:x/y/z"的資源路徑表示僅僅在bundle中查找資源"x/y/z",不在附加文件中查找。


    A resource path using the "classpath:" prefix searches the bundle classpath for matching resources.

    一個使用前綴為"classpath:"的資源路徑則在bundle的classpath中查找匹配的資源。

    All of the regular Spring resource prefixes such as "file:" and "http:" are also supported, as are the pattern matching wildcards. Resources loaded using such prefixes may come from any location, they are not restricted to being defined within the resource-loading bundle or its attached fragments.

    類似"file:"?和 "http:",Spring中列出的資源路徑前綴和通配符匹配模式也是被支持的,使用這些前綴加載的資源可能會來自任何位置,這些資源在bundle或bundle的附加片段中的定義是不被限制的。

    OSGi platforms may define their own unique prefixes for accessing bundle contents. For example, Equinox defines the 'bundleresource:' and 'bundlentry:' prefixes). These platform specific prefixes may also be used with Spring OSGi, at the cost of course of tying yourself to a particular OSGi implementation.

    OSGi平臺可能會定義它自己的唯一前綴去訪問bundle。例如,Equinox定義了'bundleresource:'和'bundlentry:'。這些平臺所特有的前綴也可能會被Spring OSGi使用,這取決于你使用的是什么OSGi實現框架(Equinox,Felix等)。

    2.5 Accessing the BundleContext

    In general there is no need to depend on any OSGi APIs when using the Spring Dynamic Modules support. If you do need access to the OSGi BundleContext object for your bundle, then Spring makes this easy to do.

    通常情況下,在使用Spring Dynamic Modules時是不需要使用任何OSGi APIs的,如果你需要在你的bundle中使用OSGi的BundleContext對象,那么Spring可以很輕松的做到這一點。

    The OSGi application context created by the Spring extender will automatically contain a bean of type BundleContext and with name bundleContext. You can inject a reference to this bean into any bean in the application context either by-name or by-type. In addition, Spring Dynamic Modules defines the interface org.springframework.osgi.context.BundleContextAware:

    如果一個bundle具有Spring-powered,由Spring extender為其創建的OSGi application context將自動包含一個類型為org.osgi.framework.BundleContext的bean,變量名為bundleContext。你可以通過bean名字或類型將這個bean注入到application context中的任何一個bean中。另外Spring Dynamic Modules還定義了這樣一個接口:

    public interface BundleContextAware {
    public void setBundleContext(BundleContext context);
    }

    Any bean implementing this interface will be injected with a reference to the bundle context when it is configured by Spring. If you wish to use this facility within a bundle, remember to import the package org.springframework.osgi.context in your bundle manifest.

    任何實現了這個接口的bean被Spring初始化時都會被注入一個bundle context。你需要在bundle的manifest中引入org.springframework.osgi.context才能使用這個功能。


    2.5.1 ThreadLocal access to BundleContext

    During creation of an application context, access to the BundleContext object for the bundle is also available through an inheritable thread-local variable. This variable is accessible via the org.springframework.osgi.context.support.LocalBundleContext class.

    在一個application context被創建的時候,通過thread-local變量也可以使用BundleContext對象。這個變量通過類org.springframework.osgi.context.support.LocalBundleContext訪問。

    public class LocalBundleContext {
    ? public static BundleContext getContext();
    }

    In addition, when an operation is invoked on an OSGi service reference injected by Spring, Spring makes sure that the invoking bundle's BundleContext is accessible on the invoking thread via the LocalBundleContext.

    另外,當一個由Spring注入的OSGi服務被調用的時候,Spring會通過LocalBundleContext確保調用的bundle的BundleContext在調用線程中是可用的。

    2.6 Stopping the extender bundle

    If the extender bundle is stopped, then all the application contexts created by the extender will be destroyed. Application contexts are shutdown in the following order:

    如果spring extender bundle被停止,那么它創建的所有application contexts將被注銷。Application contexts的關閉順序如下:

    1. Application contexts that do not export any services, or that export services that are not currently referenced, are shutdown in reverse order of bundle id. (Most recently installed bundles have their application contexts shutdown first).

      Application contexts沒有輸出任何服務或輸出的服務沒有被引用,那么則根據它們內部的bundle ID從大到小的順序關閉(跟堆棧類似,后生成的application contexts先關閉)。
    2. Shutting down the application contexts in step (1) may have released references these contexts were holding such that there are now additional application contexts that can be shutdown. If so, repeat step 1 again.

      步驟(1)中關閉的application contexts可能已經釋放了被它們持有的其他application contexts的引用,于是更多的application contexts就能夠被關閉了,如果是這樣,則重復步驟一。
    3. If there are no more active application contexts, we have finished. If there are active application contexts then there must be a cyclic dependency of references. The circle is broken by determining the highest ranking service exported by each context: the bundle with the lowest ranking service in this set (or in the event of a tie, the highest service id), is shut down. Repeat from step (1).

      如果沒有application contexts處于激活狀態,那么就完成了關閉。如果還有處于激活的application contexts,那么一定有被嵌套依賴的引用。解除這個嵌套依賴關系將由各個context輸出的最高隊列等級的服務決定:通過重復步驟(1)關閉這個嵌套依賴中級別最低的服務的bundl。


    3.0 Packaging and Deploying Spring-based OSGi applications

    A traditional Spring application uses either a single application context, or a parent context containing service layer, data layer, and domain objects with a child context containing web layer components. The application context may well be formed by aggregating the contents of multiple configuration files.

    通常Spring application使用單一的application context或是一個帶有包含web層組件的子context的父context,它們包含服務層,數據層和域對象。application context可以又多個配置文件集成的內容組成。

    When deploying an application to OSGi the more natural structure is to package the application as a set of peer bundles (application contexts) interacting via the OSGi service registry. Independent subsystems should be packaged as independent bundles or sets of bundles (vertical partitioning). A subsystem may be package in a single bundle, or divided into several bundles partitioned by layer (horizontal partitioning). A straightforward web application may for example be divided into four modules (bundles): a web bundle, service layer bundle, data layer bundle, and domain model bundle. Such an application would look like this:

    將一個應用部署到OSGi中更好的結構是將這些應用打包成一系列的bundles,它們通過OSGi service registry 相互作用。獨立的子系統應該被打包成一個獨立的bundle或劃分成多個bundles(垂直劃分)或是通過不通的層劃分成多個bundles(水平劃分)。例如,一個簡單的web application可能會被劃分成4個模塊(4個bundle):頁面顯示層bundle,服務層bundle,數據層bundle和域模型bundl。



    In this example the data layer bundle yields a data layer application context that contains a number of internal components (beans). Two of those beans are made publicly available outside of the application context by publishing them as services in the OSGi service registry.


    在這個例子中,數據層bundle生成一個包含了很多內部組件(beans)的數據層application context。在the OSGi service registry中將這些bean中的其中2個bean做為服務發布可以在application context外部使用它們。

    The service layer bundle yields a service layer application context that contains a number of internal components (beans). Some of those components depend on data layer services, and import those services from the OSGi service registry. Two of the service layer components are made externally available as services in the OSGi service registry.

    服務層bundle生成一個包含了很多內部組件(beans)的服務層application context。它們中的某些組件依賴于從OSGi service registry中引入的數據層的服務。

    The web component bundle yields a web application context that contains a number of internal components (beans). Some of those components depend on application services, and import those services from the OSGi service registry. Since the domain model bundle contributes only domain model types, but does not need to create any components of its own, it has no associated application context.

    3.1 Bundle format and Manifest headers

    Each application module should be packaged as an OSGi bundle. A bundle is essentially a jar file with a META-INF/MANIFEST.MF file containing a series of headers recognized by the OSGi Service Platform. See the OSGi Service Platform Core Specification section 3.2 for details. Some OSGi implementations may support exploded jar files, but the format remains the same.


    每一個應用模塊都應該打包成一個OSGi bundle。一個bundle其實就是一個含有META-INF/MANIFEST.MF的jar包,META-INF/MANIFEST.MF中有一系列經過OSGi服務平臺驗證的headers。關于headers的細節參見OSGi規范中的3.2節。一些OSGi實現框架可能會支持一些與眾不同的jar包,但是這些jar包關于OSGi的格式還是不變的。

    The Spring extender recognizes a bundle as "Spring-powered" and will create an associated application context when the bundle is started if one or both of the following conditions is true:

    如果滿足以下兩個條件,Spring extender會通過一個bundle的具有"Spring-powered"的驗證,當這個bundle啟動時會為其創建一個相關聯的application context:

    • The bundle classpath contains a folder META-INF/spring with one or more files in that folder with a '.xml' extension.

      這個bundle的classpath包含一個目錄META-INF/spring,這個目錄中有一個或多個擴展名為'.xml'的文件。
    • META-INF/MANIFEST.MF contains a manifest header Spring-Context.

      這個bundle中的META-INF/MANIFEST.MF文件包含一個名為Spring-Context的header。

    In addition, if the optional SpringExtender-Version header is declared in the bundle manifest, then the extender will only recognize bundles where the specified version constraints are satisfied by the version of the extender bundle (Bundle-Version). The value of the SpringExtender-Version header must follow the syntax for a version range as specified in section 3.2.5 of the OSGi Service Platform Core Specification.


    另外,如果bundle的manifest聲明了可選header - SpringExtender-Version,那么extender將僅僅認可與之版本相符的指定版本約束的bundle(bundle的Bundle-Version)。SpringExtender-Version的值必須遵循OSGi規范3.2.5節中指定的版本范圍。

    In the absence of the Spring-Context header the extender expects every ".xml" file in the META-INF/spring folder to be a valid Spring configuration file, and all directives (see below) take on their default values.

    在缺少Spring-Context的情況下,spring extender仍然認為所有META-INF/spring中".xml"的文件都是spring的配置文件,所有的header都是默認值。

    An application context is constructed from this set of files. A suggested practice is to split the application context configuration into at least two files, named by convention modulename-context.xml and modulename-osgi-context.xml. The modulename-context.xml file contains regular bean definitions independent of any knowledge of OSGi. The modulename-osgi-context.xml file contains the bean definitions for importing and exporting OSGi services. It may (but is not required to) use the Spring Dynamic Modules OSGi schema as the top-level namespace instead of the Spring 'beans' namespace.


    application context就是根據這些文件(META-INF/spring中".xml"的文件)構造的。一個推薦的做法是將application context配置文件至少分割成2個文件,習慣上命名為 [模塊名-context.xml] 和[模塊名-osgi-context.xml]。modulename-context.xml文件包含了不依賴與OSGi相關的bean的定義(可以理解為普通bean定義)。modulename-osgi-context.xml文件則定義那些引入或輸出OSGi服務的bean。這可能需要使用Spring Dynamic Modules的OSGi schema做為頂級命名空間,取代spring的'bean'命名空間,但這不是必須的。

    =====================以下是 Spring-Context的相關內容和配置,主要意思如下:

    1.如果在Spring-Context指定了配置文件,那么extender將忽略 META-INF/spring 中的配置文件,除非明確指定。
    2.可以用通配符,例如Spring-Context: osgi-*;
    3.create-asynchronously=false(默認值是true)?,使用同步方式創建該bundle的application context。有一點需要注意,同步創建application context的過程是在OSGi的事件線程中進行的,它將阻塞這個線程的事件發送,直到完成application context的初始化。如果這個過程中發生了錯誤,那么將出現一個FrameworkEvent.ERROR,但是bundle的狀態仍然還是ACTIVE。
    4.wait-for-dependencies和timeout,從字面意思就能看出來了。
    5.publish-context:=false(默認值是true),不將application context作為一個服務發布。

    The Spring-Context manifest header may be used to specify an alternate set of configuration files. The resource paths are treated as relative resource paths and resolve to entries defined in the bundle and the set of attached fragments. When the Spring-Context header defines at least one configuration file location, any files in META-INF/spring are ignored unless directly referenced from the Spring-Context header.

    The syntax for the Spring-Context header value is:

    Spring-Context-Value ::= context ( ',' context ) *
    context ::= path ( ';' path ) * (';' directive) *
    

    This syntax is consistent with the OSGi Service Platform common header syntax defined in section 3.2.3 of the OSGi Service Platform Core Specification.

    For example, the manifest entry:

    Spring-Context: config/account-data-context.xml, config/account-security-context.xml

    will cause an application context to be instantiated using the configuration found in the files account-data-context.xml and account-security-context.xml in the bundle jar file.

    A number of directives are available for use with the Spring-Context header. These directives are:

    • create-asynchronously (false|true): controls whether the application context is created asynchronously (the default), or synchronously.

    For example:

    Spring-Context: *;create-asynchronously=false
    

    Creates an application context synchronously, using all of the "*.xml" files contained in the META-INF/spring folder.

    Spring-Context: config/account-data-context.xml;create-asynchrously:=false

    Creates an application context synchronously using the config/account-data-context.xml configuration file. Care must be taken when specifying synchronous context creation as the application context will be created on the OSGi event thread, blocking further event delivery until the context is fully initialized. If an error occurs during the synchronous creation of the application context then a FrameworkEvent.ERROR event is raised. The bundle will still proceed to the ACTIVE state.

    • wait-for-dependencies (true|false): controls whether or not application context creation should wait for any mandatory service dependencies to be satisfied before proceeding (the default), or proceed immediately without waiting if dependencies are not satisfied upon startup.

    For example:

    Spring-Context: config/osgi-*.xml;wait-for-dependencies:=false
    

    Creates an application context using all the files matching "osgi-*.xml" in the config directory. Context creation will begin immediately even if dependencies are not satisfied. This essentially means that mandatory service references are treated as though they were optional - clients will be injected with a service object that may not be backed by an actual service in the registry initially. See section 4.2 for more details.

    • timeout (300): the time to wait (in seconds) for mandatory dependencies to be satisfied before giving up and failing application context creation. This setting is ignored if wait-for-dependencies:=false is specified. The default is 5 minutes (300 seconds).

    For example:

    Spring-Context: *;timeout:=60
    
    • publish-context (true|false): controls whether or not the application context object itself should be published in the OSGi service registry. The default is to publish the context.

    For example:

    Spring-Context: *;publish-context:=false
    

    If there is no Spring-Context manifest entry, or no value is specified for a given directive in that entry, then the directive takes on its default value.



    3.2 Required Spring Framework and Spring Dynamic Modules Bundles

    The Spring Dynamic Modules project provides an number of bundle artifacts that must be installed in your OSGi platform in order for the Spring extender to function correctly:

    Spring Dynamic Modules提供了很多現成的bundle,要使用Spring extender必須將這些bundle安裝到OSGi平臺中:

    • The extender bundle itself, org.springframework.osgi.extender
    • The core implementation bundle for the Spring Dynamic Modules support, org.springframework.osgi.core
    • The Spring Dynamic Modules i/o support library bundle, ' org.springframework.osgi.io

    In addition the Spring Framework provides a number of bundles that are required to be installed. As of release 2.5 of the Spring Framework, the Spring jars included in the Spring distribution are valid OSGi bundles and can be installed directly into an OSGi platform. The minimum required set of bundles is:

    另外spring還提供了很多它自己的bundle,這些bundle可以直接被安裝到OSGi平臺中。要使用spring的最低要求需要以下幾個bundle:

    • spring-core.jar (bundle symbolic name org.springframework.core)
    • spring-context.jar (bundle symbolic name org.springframework.context)
    • spring-beans.jar (bundle symbolic name org.springframework.beans)
    • spring-aop.jar (bundle symbolic name org.springframework.aop)

    In additional the following supporting library bundles are required. OSGi-ready versions of these libraries are shipped with the Spring Dynamic Modules distribution.

    以下幾個bundle是spring的依賴bundle,可以在Spring Dynamic Modules的分發包中找到它們:

    • aopalliance
    • backport-util (for JDK 1.4)
    • cglib-nodep
    • commons-logging (SLF4J version highly recommended)

    ?

    3.3 Importing and Exporting packages

    Refer to the OSGi Service Platform for details of the Import-Package and Export-Package manifest headers. Your bundle will need an Import-Package entry for every external package that the bundle depends on. If your bundle provides types that other bundles need access to, you will need Export-Package entries for every package that should be available from outside of the bundle.

    這部份是關于OSGi平臺MANIFEST中Import-PackageExport-Package的細節描述。你的bundle中的MANIFEST.MF需要一個Import-Package來引入它所依賴的外部package。如果你的bundle提供的type需要被其他bundle使用,你需要使用Export-Package將每一個對外部bundle可用的package輸出。


    3.4 Considerations when using external libraries

    Many enterprise application libraries assume that all of the types and resources that comprise the application are accessible through the context class loader. In OSGi R4, the set of types and resources available through the context class loader is undefined. Libraries that generate new classes dynamically can also cause problems in an OSGi environment.


    許多企業級應用程序中的libraries(假設這個libraries是組成這個用應用程序的所有types和資源)都能通過context class loader訪問和使用,但是在OSGi R4規范中,確不是這樣定義的,同樣,在OSGi環境中libraries動態生成classes也會產生問題。

    Spring Dynamic Modules guarantees that during the creation of an application context on behalf of a given bundle, all of that types and resources on the bundle's classpath are accessible via the context class loader. Spring Dynamic Modules also allows you to control what is accessible through the context class loader when invoking external services and when servicing requests on exported services. See section 4 for details on this.

    Spring Dynamic Modules確保了在為bundle生成application context的時候,bundle的classpath下的所有types和資源都可以通過這個application context的classloader去訪問和使用。當調用外部服務和響應對輸出服務的請求時,Spring Dynamic Modules也允許你控制所有能通過context的classloader訪問的資源。具體細節參加第四部份。

    Work is underway in the OSGi R5 timeframe to provide standardized support for dealing with generated classes and implicit class path dependencies introduced by third-party libraries. In the interim you may need to rely on workarounds such as the DynamicImport-Package manifest header, or the facilities provided by specific OSGi implementations such as Equinox's buddy mechanism. The Spring Dynamic Modules tutorial contains more detail on known issues with common enterprise libraries and the workarounds.

    3.5 Diagnosing problems

    Your chosen OSGi platform implementation should be able to provide you with a good deal of information about the current status of the OSGi environment. For example, starting Equinox with the -console argument provides a command-line console through which you can determine which bundles are installed and their states, the packages and services exported by bundles, find out why a bundle has failed to resolve, and drive bundles through the lifecycle.


    OSGi實現框架應該提供很多關于OSGi環境當前狀態的信息。例如通過參數-console啟動的Equinx會提供一個命令行控制臺,通過這個控制臺你可以看到哪些bundle被安裝了,這些bundle的狀態,這些bundle輸出的package和服務,找到bundle解析失敗的原因,改變bundle生命周期狀態。

    In addition, Spring itself and the Spring Dynamic Modules bundles contain extensive logging instrumentation that can help you diagnose problems. The recommended approach is to deploy the Simple Logging Facade for Java (
    slf4j) slf4j-api.jar and slf4j-log4j13.jar bundles (the jar files distributed by the project are valid OSGi bundles). Then you simply need to create a log4j.properties file in the root of your bundle classpath.

    另外,spring本身和Spring Dynamic Modules bundles包含了logging的擴展包,能幫助你找到問題。推薦的做法是將Simple Logging Facade for Java (slf4j)的slf4j-api.jar和slf4j-log4j13.jar部署成bundle(分發包中的jar包已經是可用的OSGi bundle了),然后你只需要簡單的將log4j.properties放到bundle classpath的根目錄下。


    4.0 The Service Registry

    The OSGi service registry enables a bundle to publish objects to a shared registry, advertised via a given set of Java interfaces. Published services also have service properties associated with them in the registry.

    OSGi服務注冊器(The OSGi service registry )允許一個bundle將對象發布到一個共享的注冊器中,通過一系列java 接口發布注冊通知,同時也會有一些服務屬性伴隨著已經發布的服務。

    Spring Dynamic Modules provides an 'osgi' namespace for Spring (see Appendix B) that can be used to export Spring beans as OSGi services, and to define references to services obtained via the service registry. The namespace elements may be used nested inside another top-level namespace (typically the Spring 'beans' namespace), or within the top-level osgi element.

    Spring Dynamic Modules提供了一個叫'osgi'的命名空間(見附錄B),它可以用來將spring bean做為OSGi服務輸出,也可以用來定義從service registry中獲得的服務的引用。這個命名空間節點可以被嵌套在其他的頂級命名空間中(特別是Spring的'bean'名字空間),或是在頂級命名空間為'osgi'的節點中。

    The following example shows the use of the osgi namespace within the familiar Spring beans element:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:osgi="http://www.springframework.org/schema/osgi"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/osgi
    http://www.springframework.org/schema/osgi/spring-osgi.xsd">
    <!-- use the OSGi namespace elements qualified with 'osgi:' -->
    <osgi:service id="simpleServiceOsgi" ref="simpleService"
    interface="org.xyz.MyService" />
    </beans>

    Using the OSGi namespace as a top-level namespace the same service would be declared as follows:

    <?xml version="1.0" encoding="UTF-8"?>
    <osgi xmlns="http://www.springframework.org/schema/osgi"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/osgi
    http://www.springframework.org/schema/osgi/spring-osgi.xsd">
    <!-- use the OSGi namespace elements directly -->
    <service id="simpleServiceOsgi" ref="simpleService"
    interface="org.xyz.MyService" />
    </osgi>
    

    Using the OSGi namespace as a top-level namespace is particularly convenient when following the recommendation of section 3.1 to use a dedicated configuration file for all OSGi-related declarations.

    使用OSGi名字空間做為頂級名字空間是推薦做法。

    4.1 Exporting a Spring bean as an OSGi service

    The service element is used to define a bean representing an exported OSGi service. At a minimum you must specify the bean to be exported, and the service interface that the service offers.

    For example, the declaration

    <service>節點用來定義將一個bean描述成一個被輸出的OSGi服務,而這至少需要你指定這個要被輸出為服務的bean,
    和服務的接口類型,例如這個聲明:

    <service ref="beanToPublish" interface="com.xyz.MessageService"/>

    exports the bean with name beanToPublish with interface com.xyz.MessageService. The published service will have a service property with the name org.springframework.osgi.beanname set to the name of the target bean being registered (beanToPublish in this case).

    這個聲明將一個名字為'beanToPublish'輸出為接口類型為com.xyz.MessageService的服務,這個服務將會有一個名字為org.springframework.osgi.beanname的service屬性,它的值將被設置為bean的名字(在本例中為 beanToPublish)。

    The bean defined by the service element is of type org.osgi.framework.ServiceRegistration and is the ServiceRegistration object resulting from registering the exported bean with the OSGi service registry. By giving this bean an id you can inject a reference to the ServiceRegistration object into other beans if needed. For example:

    由<service>節點定義的bean的類型是org.osgi.framework.ServiceRegistration,是通過將bean輸出的服務注冊到the OSGi service registry中形成的ServiceRegistration對象。通過設置一個ID屬性可以將這個對象的引用注入到任何一個bean中,例如:

    <service id="myServiceRegistration" ref="beanToPublish"
    ??? interface="com.xyz.MessageService"/>

    As an alternative to exporting a named bean, the bean to be exported to the service registry may be defined as an anonymous inner bean of the service element. Typically the top-level namespace would be the beans namespace when using this style:

    做為可選擇的bean定義,一個輸出到service registry中的bean還可以被定義為一個<service>節點的匿名內部bean。使用下面這種風格的定義是使用<beans>做為頂級名字空間的典型代表。

    <osgi:service interface="com.xyz.MessageService">
    ? <bean class="SomeClass">
    ???? ...
    ? </bean>
    </osgi:service>

    If the bean to be exported implements the org.osgi.framework.ServiceFactory interface then the ServiceFactory contract is honored as per section 5.6 of the OSGi Service Platform Core Specification. As an alternative to implementing this OSGi API, Spring Dynamic Modules introduces a new bean scope, the bundle scope. When a bean with bundle scope is exported as an OSGi service then one instance of the bean will be created for each unique client (service importing) bundle that obtains a reference to it through the OSGi service registry. When a service importing bundle is stopped, the bean instance associated with it is disposed. To declare a bean with bundle scope simply use the scope attribute of the bean element:

    按照OSGi服務平臺核心規范,如果一個被輸出的bean實現了接口org.osgi.framework.ServiceFactory,那么這個ServiceFactory對象與bundle間將會產生一個很受重視的關系。Spring Dynamic Modules引入了一個新的bean范圍 - bundle范圍。當一個具有bundle范圍的bean做為OSGi服務輸出的時候,這個bean的一個實例對象將被生成,每一個不同的客戶端bundle(引用這個服務的bundle)都通過OSGi service registry獲取它。當其中一個引用這個服務的bundle停止時,它所獲取的這個bean的實例對象將被除去。要聲一個bundle范圍的bean,只需要添加一個'scope'屬性元素就可以了:

    <osgi:service ref="beanToBeExported" interface="com.xyz.MessageService"/>
    <bean id="beanToBeExported" scope="bundle" class="com.xyz.MessageServiceImpl"/>


    4.1.1 Controlling the set of advertised service interfaces for an exported service

    The OSGi Service Platform Core Specification defines the term service interface to represent the specification of a service's public methods. Typically this will be a Java interface, but the specification also supports registering service objects under a class name, so the phrase service interface can be interpreted as referring to either an interface or a class.

    OSGi服務平臺核心規范定義了術語"service interface"用于描述一個服務的公共方法。具有代表性的就是Java interface,不過OSGi規范也支持通過類名來注冊服務對象,所以短語"service interface"也能被理解成接口或類。

    There are several options for specifying the service interface(s) under which the exported service is registered. The simplest mechanism, shown above, is to use the interface attribute to specify a fully-qualified interface name. To register a service under multiple interfaces the nested interfaces element can be used in place of the interface attribute.

    這里也有一些選項用于注冊指定這個被輸出的服務實現了的接口。如下面所顯示的,最簡單的辦法是使用interface屬性指定一個全路徑的接口名。如果要注冊一個實現了多接口的服務,可以使用interfaces 節點代替interface屬性。

    <osgi:service ref="beanToBeExported">
    ? <osgi:interfaces>
    ???? <value>com.xyz.MessageService</value>
    ???? <value>com.xyz.MarkerInterface</value>
    ? </osgi:interfaces>
    </osgi:service>

    Using the auto-export attribute you can avoid the need to explicitly declare the service interfaces at all. The auto-export attribute can have one of four values:

    使用'auto-export'屬性,可以不用聲明一個服務接口,'auto-export'屬性具有如下4個值中的其中一個:

    • disabled : the default value; no auto-detected of service interfaces is undertaken and the interface attribute or interfaces element must be used instead.

      disabled: 默認值,具有自動檢測功能的服務接口將不被啟動,必須使用interface屬性或interfaces節點。
    • interfaces : the service will be registered using all of the Java interface types implemented by the bean to be exported

      interfaces: 所有被輸出的bean所實現的所有java接口將自動被注冊。
    • class-hierarchy : the service will be registered using the exported bean's implementation type and super-types

      class-hierarchy: 這個bean的類和它的父類將被自動注冊。
    • all : the service will be registered using the exported bean's implementation type and super-types plus all interfaces implemented by the bean.

      all: 包含 interfaces和class-hierarchy

    For example, to automatically register a bean under all of the interfaces that it supports you would declare:

    <service ref="beanToBeExported" auto-export="interfaces"/>
    

    Given the interface hierarchy:

    public interface SuperInterface {}
    
    public interface SubInterface extends SuperInterface {}
    

    then a service registered as supporting the SubInterface interface is not considered a match in OSGi when a lookup is done for services supporting the SuperInterface interface. For this reason it is a best practice to export all interfaces supported by the service being registered explicitly, using either the interfaces element or auto-export="interfaces".

    在OSGi中,當一個SuperInterface的匹配查找結束時,一個支持SubInterface 的注冊的服務是不匹配的。這對于使用使用interfaces 節點或auto-export="interfaces"輸出被明確注冊的服務所支持的接口是很好的實踐。

    Note that when using auto-export, only types visible to the bundle exporting the service are registered. For example, a super-interface SI would not be exported as a supported service interface even when using auto-export="interfaces" if SI was not on the exporting bundle's classpath.

    注意,當使用auto-export時,僅僅只有對輸出服務的bundle可見的types(接口或類)才會被注冊。例如,一個super-interface SI,如果它不在輸出bundle的classpath中,即使當使用auto-export="interfaces",它也不會做為一個被服務支持的接口輸出。


    4.1.2 Controlling the set of advertised properties for an exported service

    As previously described, an exported service is always registered with the service property org.springframework.osgi.beanname set to the name of the bean being exported. Additional service properties can be specified using the nested service-properties element. The service-properties element contains key-value pairs to be included in the advertised properties of the service. The key must be a string value, and the value must be a type recognized by OSGi Filters. See section 5.5 of the OSGi Service Platform Core Specification for details of how property values are matched against filter expressions.

    前面已經描述過,一個輸出的服務被注冊后,會有一個服務屬性org.springframework.osgi.beanname,值就是被輸出的bean的名字??梢允褂们短坠濣cservice-properties指定一些附加屬性,service-properties節點有包含在服務的通知屬性中的鍵-值對。key必須是一個string,value必須是一個經過OSGi Filters驗證的type。對于匹配OSGi filters表達式的細節可以參照OSGi規范5.5節。

    The service-properties element must contain at least one nested entry element from the Spring beans namespace.

    service-properties節點必須包含至少一個Spring beans名字空間的entry 節點。

    For example:

    <service ref="beanToBeExported" interface="com.xyz.MyServiceInterface">
      <service-properties>
        <beans:entry key="myOtherKey" value="aStringValue"/>
        <beans:entry key="aThirdKey" value-ref="beanToExposeAsProperty"/>
      <service-properties>
    </service>
    

    The Spring Dynamic Modules roadmap includes support for exporting properties registered in the OSGi Configuration Administration service as properties of the registered service. See Appendix A for more details.

    Spring Dynamic Modules roadmap 包含了支持將屬性做為一個被注冊了的服務的屬性注冊到OSGi Configuration Administration service 中。


    4.1.3 The depends-on attribute

    Spring will manage explicit dependencies of a service element, ensuring for example that the bean to be exported as a service is fully constructed and configured before exporting it. If a service has implicit dependencies on other components (including other service elements) that must be fully initialized before the service can be exported, then the optional depends-on attribute can be used to express these dependencies.

    Spring會管理服務元素中明示性的依賴關系,例如確保哪些被做為服務輸出的bean在輸出之前被完全構造和配置。如果一個服務隱含依賴于其他組件(包括其他服務元素),這個組件在服務被輸出之前要被完全初始化,那么可選的屬性depends-on能用來表示這種依賴關系。

    <service ref="beanToBeExported" interface="com.xyz.MyServiceInterface"
    ???? depends-on="myOtherComponent"/>


    4.1.4 The ranking attribute

    When registering a service with the service registry, you may optionally specify a service ranking (see section 5.2.5 of the OSGi Service Platform Core Specification). When a bundle looks up a service in the service registry, given two or more matching services the one with the highest ranking will be returned. The default ranking value is zero. To explicitly specify a ranking value for the registered service, use the optional ranking attribute.

    當注冊一個服務時,你可能會隨意指定一個ranking(關于ranking,參見OSGi規范5.2.5節)。當一個bundle查找一個服務時,ranking最高的與之匹配的服務將會被返回。默認的ranking值是0.使用可選的ranking屬性可以為注冊的服務指定一個ranking值。

    <service ref="beanToBeExported" interface="com.xyz.MyServiceInterface"
    ? ranking="9"/>


    4.1.5 The context-classloader attribute

    The OSGi Service Platform Core Specification (most current version is 4.1 at time of writing) does not specify what types and resources are visible through the context class loader when an operation is invoked on a service obtained via the service registry. Since some services may use libraries that make certain assumptions about the context class loader, Spring Dynamic Modules enables you to explicitly control the context class loader during service execution. This is achieved using the option context-classloader attribute of the service element.

    OSGi規范沒有指定當通過service registry獲取服務的方法被調用時,什么樣的types和資源對context class loader可見。所以假設某個服務如果要用到context class loader相關的libraries時,Spring Dynamic Modules允許你在服務執行期明確的控制context class loader,通過service元素的可選屬性'context-classloader'來完成。

    The permissible values for the context-classloader attribute are unmanaged (the default) and service-provider. When the service-provider value is specified, Spring Dynamic Modules ensures that the context class loader can see all of the resources on the class path of the bundle defining the service.

    'context-classloader'屬性允許的值只有2個 'unmanaged'(默認) 和 'service-provider',當指定'service-provider'值時,Spring Dynamic Modules確保了context class loader 能看見定義這個服務的bundle的classpath中所有的資源。

    4.1.6 Service registration and unregistration lifecycle

    The service defined by a service element is registered with the OSGi service registry when the application context is first created. It will be unregistered automatically when the bundle is stopped and the application context is disposed.

    當application context第一次被創建時,由<service>元素定義的服務通過OSGi service registry 注冊。這個服務將會在bundle停止和application context被注銷時自動注銷。

    An exported service may depend, either directly or indirectly, on other services in order to perform its function. If one of these services is considered a mandatory dependency (see section 4.2) and the dependency can no longer be satisfied (because the backing service has gone away and there is no suitable replacement available) then the exported service that depends on it will be automatically unregistered from the service registry - meaning that it is no longer available to clients. If the mandatory dependency becomes satisfied once more (by registration of a suitable service), then the exported service will be re-registered in the service registry.

    一個輸出的服務(ServiceA)可能會因為功能需要而直接或間接地依賴其他服務。如果這些服務中的其中一個服務(ServiceB)匹配ServiceA的強制依賴,并且這個強制依賴關系不再satisfied(因為ServiceB不再可用),那么這個輸出的服務(ServiceA)將會自動從service registry中注銷,也就是說不再對客戶端有效。如果這個強制依賴關系再次變得satified(通過注冊一個匹配這個強制依賴關系的服務,可能是ServiceB也可能是其他服務),那么這個輸出的服務(ServiceA)將被重新注冊到service registry。

    This automatic unregistering and re-registering of exported services based on the availability of mandatory dependencies only takes into account declarative dependencies. If exported service S depends on bean A, which in turn depends on mandatory imported service M, and these dependencies are explicit in the Spring configuration file as per the example below, then when M becomes unsatisfied S will be unregistered. When M becomes satisfied again, S will be re-registered.

    輸出服務基于強制依賴的自動注銷和重新注冊僅僅用在聲明性的依賴關系中。在下面給的例子中,輸出的服務S依賴bean A,bean A引入了服務M,那么當M變得unsatisfied時,S將會被自動注銷,當M重新變得satisfied是,S將重新注冊。

    <osgi:service id="S" ref="A" interface="SomeInterface"/>

    <bean id="A" class="SomeImplementation">
    ?? <property name="helperService" ref="M"/>
    </bean>

    <!-- the reference element is used to refer to a service
    ???? in the service registry -->
    <osgi:reference id="M" interface="HelperService"
    ???? cardinality="1..1"/>

    If however the dependency from A on M is not established through configuration as shown above, but instead at runtime through for example passing a reference to M to A without any involvement from the Spring container, then Spring Dynamic Modules will not track this dependency.

    If you need to take some action when a service is unregistered because its dependencies are not satisfied (or when it is registered), then you can define a listener bean using the nested registration-listener element.

    如果你想在一個服務因為它的依賴關系不再satisfied(或注冊)時做點什么,可以使用嵌套元素registration-listener定義個監聽bean

    The declaration of a registration listener must use either the ref attribute to refer to a top-level bean definition, or declare an anonymous listener bean inline. For example:

    聲明一個注冊監聽器必須在頂級bean定義中使用ref 屬性或是在它里面聲明一個匿名監聽器bean。

    <!-- example service declaration with two listeners -->

    <service ref="beanToBeExported" interface="SomeInterface">
    ? <registration-listener ref="myListener"
    ??? registration-method="serviceRegistered"
    ??? unregistration-method="serviceUnregistered"/>
    ? <registration-listener
    ???? registration-method="register"
    ???? unregistration-method="unregister">
    ???? <bean class="SomeListenerClass"/>
    ? </registration-listener>
    </service>

    The optional registration-method and unregistration-method attributes specify the names of the methods defined on the listener bean that are to be invoked during registration and unregistration. A registration callback method must have a signature matching the following format

    可選的registration-method和unregistration-method屬性指定了定義在監聽bean中的方法的名字,它們會在服務被注冊或注銷的時候調用。一個注冊回調方法必須匹配下面的格式:

    public void anyMethodName(ServiceType serviceInstance);

    where ServiceType can be any type compatible with the exported service interface of the service.

    這里的ServiceType 可以是任何type,當然它必須要兼容你要監聽的服務的類型

    An unregistration callback method must have a signature of the form

    public void anyMethodName(ServiceType serviceInstance);
    

    where ServiceType can be any type compatible with the exported service interface of the service.

    The register callback is invoked when the service is initially registered at startup, and whenever it is subsequently re-registered. The unregister callback is invoked immediately after the service is unregistered, including when the service is unregistered because the bundle is stopping.

    注冊時回調方法會在系統啟動時初次注冊服務時調用,也會在服務被重新注冊時調用。注銷回調方法會在服務被注銷后立即調用,包括bundle停止時引起的服務注銷。


    4.2 Defining references to OSGi services

    Spring Dynamic Modules supports the declaration of beans that represent services accessed via the OSGi Service Registry. In this manner references to OSGi services can be injected into application components. The service lookup is made using the service interface type that the service is required to support, plus an optional filter expression that matches against the service properties published in the registry.

    Spring Dynamic Modules支持將bean聲明為可通過OSGi Service Registry訪問的服務,這可以將OSGi services的引用注入到應用組件中。服務的查找是通過使用服務支持的接口類型,再加上可選的匹配發布在registry中的服務屬性的過濾器表達式。

    For some scenarios, a single matching service that meets the application requirements is all that is needed. The reference element defines a reference to a single service that meets the required specification. In other scenarios, especially when using the OSGi whiteboard pattern, references to all available matching services are required. Spring Dynamic Modules supports the management of this set of references as a List, Set.

    在某些情況下,一個與應用需求相應的單一匹配是必須的,<reference>元素定義了一個相應的單一服務的引用。在其他情況下,尤其是當使用OSGi whiteboard pattern時,需要所有可用的匹配服務的應用。Spring Dynamic Modules支持將這些應用做為List或Set去管理。

    4.2.1 Referencing an individual service

    The reference element is used to define a reference to a service in the service registry. The interface attribute identifies the service interface that a matching service must implement. For example, the following declaration creates a bean messageService, which is backed by the service returned from the service registry when querying it for a service offering the MessageService interface.

    <reference>元素用來定一個被注冊到service registry中的服務的引用。interface 屬性用來識別服務接口。例如,下面的聲明創建了一個bean - messageService,它實際上是通過查找名字為messageService,接口為MessageService 得到的服務。

    <reference id="messageService"
    ?? interface="com.xyz.MessageService"/>

    If there are several services in the service registry then the service returned is the service that would be returned by a call to BundleContext.getServiceReference. This means that the service with the highest ranking will be returned, or if there is a tie in ranking, the service with the lowest service id (the service registered first with the framework) is returned.

    如果service registry中有多個服務,那么將通過BundleContext.getServiceReference來返回服務。也就是說返回的這個服務具有最高隊列等級,或是如果有一個tie在隊列等級中,則返回id最小的那個服務(第一個被注冊的服務)。

    The bean defined by the reference element implements all of the registered interfaces of the service that are visible to the bundle. If the registered service interfaces include Java class types (as opposed to interface types) then support for these types is subject to the restrictions of Spring's AOP implementation (see the Spring Reference Guide). In short, cglib must be available, and final methods are not supported.

    使用<reference>定義的bean要實現所有注冊了的服務接口,這些接口需要對bundle可見。如果注冊的服務接口包含了java類(非java接口),那么將會影響到Spring的AOP功能。簡單的說,會影響到cglib,并且final方法不被支持。


    If the property into which a reference bean is to be injected has type ServiceReference (instead of the service interface supported by the reference), then the OSGi ServiceReference for the service will be injected in place of the service itself.

    如果一個服務的某個屬性,被注入的bean的的引用的類型是ServiceReference(它不是被引用所支持的服務接口),那么這個服務的服務引用將被注入,而不是這個服務本身。

    4.2.1.1 The filter attribute

    The optional filter attribute can be used to specify an OSGi filter expression and constrains the service registry lookup to only those services that match the given filter.

    可選屬性filter 用來指定一個OSGi過濾器表達式,用于service registry查找那些僅僅匹配過濾器條件的服務。

    For example:

    <reference id="asyncMessageService" interface="com.xyz.MessageService"
      filter="(asynchronous-delivery=true)"/>
    
    4.2.1.2 The bean-name attribute

    The bean-name attribute is a convenient short-cut for specifying a filter expression that matches on the bean-name property automatically set when exporting a bean using the service element (see section 4.1).

    屬性bean-name是一個方便的short-cut,當使用<service >輸出一個bean時,用于指定一個匹配自動設置的bean-name屬性的過濾表達式。

    For example:

    <reference id="messageService" interface="com.xyz.MessageService"
       bean-name="defaultMessageService"/>
    
    4.2.1.3 The cardinality attribute

    The cardinality attribute is used to specify whether or not a matching service is required at all times. A cardinality value of 1..1 (the default) indicates that a matching service must always be available. A cardinality value of 0..1 indicates that a matching service is not required at all times (see section 4.2.1.6 for more details). A reference with cardinality 1..1 is also known as a mandatory service reference and by default application context creation is deferred until the reference is satisfied.

    屬性cardinality 用于指定一個匹配的服務是否在任何時候都需要它可用。值'1..1'(默認值)表示一個匹配的服務必須總是可用。值'0..1'表示一個匹配服務不一定在任何時候都需要它可用(細節參見4.2.1.6)。一個cardinality值為'1..1'的服務就已經構成了一個強制依賴服務,而且默認情況下會延遲創建它的application context,直到這個依賴關系變得satisfied。

    Note: it is an error to declare a mandatory reference to a service that is also exported by the same bundle, this behavior can cause application context creation to fail through either deadlock or timeout.

    注意:聲明一個強制依賴引用到一個服務,而這個服務和這個引用被同一個bundle所輸出,這是錯誤的,會導致創建application context是發生死鎖或超時。

    4.2.1.4 The depends-on attribute

    The depends-on attribute is used to specify that the service reference should not be looked up in the service registry until the named dependent bean has been instantiated.

    屬性depends-on用于指定一個服務不應該在service registry中查找和使用直到與這個屬性值相同的bean被初始化。

    4.2.1.5 The context-classloader attribute

    The OSGi Service Platform Core Specification (most current version is 4.1 at time of writing) does not specify what types and resources are visible through the context class loader when an operation is invoked on a service obtained via the service registry. Since some services may use libraries that make certain assumptions about the context class loader, Spring Dynamic Modules enables you to explicitly control the context class loader during service invocation. This is achieved using the option context-classloader attribute of the reference element.

    The permissible values for the context-classloader attribute are unmanaged (the default), client, and service-provider. When the client value is specified, the context class loader at the point of service invocation is guaranteed to be able to see types on the classpath of the invoking bundle. When the service-provider value is specified, the context class loader is guaranteed to be able to see types on the classpath of the bundle that exported the service.

    4.2.1.6 Dealing with Service dynamics

    The bean defined by the reference element is unchanging throughout the lifetime of the application context (the object reference remains constant). However, the OSGi service that backs the reference may come and go at any time. For a mandatory service reference (cardinality 1..1), creation of the application context will block until a matching service is available. For an optional service reference, the reference bean will be created immediately, regardless of whether or not there is currently a matching service.

    在application context 的生命周期中,使用<reference >定義的bean不會發生改變,盡管如此,引用的這個服務可能隨時不可用。對于一個強制依賴的服務引用(包括使用cardinality 1..1),將延遲創建application context 知道匹配服務都可用。對于一個可選的服務引用,這個引用的bean會立即生成application context,與是否是當前匹配服務無關。

    When the service backing a reference bean goes away, Spring Dynamic Modules tries to replace the backing service with another service matching the reference criteria. An application may be notified of a change in backing service by registering a listener. If no matching service is available, then the reference is said to be unsatisfied. An unsatisfied mandatory service causes any exported service (service bean) that depends on it to be unregistered from the service registry until such time as the reference is satisfied again.

    當一個被bean引用的服務不可用時,Spring Dynamic Modules會嘗試使用另一個匹配引用標準的服務替換掉這個服務。一個application context 可能會被一個注冊的監聽器通知這個服務的變化。如果沒有任何服務匹配這個引用標準,則意味著這個引用變得unsatisfied。一個 unsatisfied的強制依賴服務會使依賴它的其他服務也變得 unsatisfied直到這個引用重新變得satisfied。

    When an operation is invoked on an unsatisfied reference bean (either optional or mandatory), the invocation blocks until the reference becomes satisfied. The optional timeout attribute of the reference element enables a timeout value (in milliseconds) to be specified. If a timeout value is specified and no matching service becomes available within the timeout period, an unchecked ServiceUnavailableException is thrown.

    當調用一個 unsatisfied的bean引用(可選依賴或強制依賴)時,這個調用將會被阻塞直到這個引用變得satisfied。<reference >的可選屬性timeout 可以指定一個阻塞的超時時間,如果在指定的超時時間內沒有一個匹配的服務可用,將拋出一個ServiceUnavailableException 異常。

    When using the osgi element to enclose service and reference elements, the default-timeout attribute may be used to specify a default timeout for all reference elements that do not explicitly specify one. For example:

    可以用下面的方式為所有的引用指定共同的超時時間,同時也可以單獨指定超時時間:

    <osgi default-timeout="5000">

    ? <!-- we will wait up to 5 seconds for a matching service on
    ?????? invocation -->
    ? <reference id="someService" interface="com.xyz.AService"/>

    ? <!-- we will wait only 1 second for a matching service on
    ?????? invocation -->
    ? <reference id="someOtherService" interface="com.xyz.BService"
    ?????? timeout="1000"/>

    </osgi>

    For applications that need to be aware of when the service backing a reference bean is bound and unbound, it is possible to register one or more listeners using the nested listener element. The listener element refers to a bean (either by name, or by defining one inline) that will receive bind and unbind notifications. If this bean implements Spring's org.springframework.osgi.service.TargetSourceLifecycleListener interface, then the bind and unbind operations in this interface will be invoked. Instead of implementing this interface (or in addition), custom bind and unbind callback methods may be named.

    對于一個應用,當一個引用bean服務 ( the service backing a reference bean? - 使用<reference>引用一個被Spring用<service>輸出的bean形成的服務 ) ?被綁定或解除綁定時,可以使用<listener>設置一個或多個監聽器。<listener >引入的bean會收到bind和unbind的通知。如果這個bean實現了Spring的org.springframework.osgi.service.TargetSourceLifecycleListener接口,那么與這個接口響應的方法將被調用,也可以自己定義bind和unbind方法。

    An example of declaring a listener that implements TargetSourceLifecycleListener:

    <reference id="someService" interface="com.xyz.MessageService">
      <listener ref="aListenerBean"/>
    </reference>
    

    An example of declaring an inline listener bean with custom bind and unbind methods:

    <reference id="someService" interface="com.xyz.MessageService">
      <listener bind-method="onBind" unbind-method="onUnbind">
         <beans:bean class="MyCustomListener"/>
      </listener>
    </reference>
    

    If the listener bean implements the TargetSourceLifecyleListener interface and the listener definition specifies custom bind and unbind operations then both the TargetSourceLifecycleListener operation and the custom operation will be invoked, in that order.

    如果一個監聽bean實現了TargetSourceLifecyleListener 接口并且自定義了bind和unbind方法,那么先是TargetSourceLifecycleListener 接口的相應方法被調用,然后自定義的方法接著被調用。

    The signature of a custom bind or unbind method must be one of:

    public void anyMethodName(ServiceType service, Dictionary properties);
    
    public void anyMethodName(ServiceType service, Map properties);
    
    public void anyMethodName(ServiceReference ref);
    

    If the method signature has a single argument of type ServiceReference then the ServiceReference of the service will be passed to the callback in place of the service object itself.

    如果這個回調方法只有一個類型為ServiceReference 的參數,那么這個服務的服務引用將被傳入這個回調方法,而不是這個服務本身。

    where ServiceType can be any type that is assignable from the reference interface type. The properties parameter contains the set of properties that the service was registered with.

    ServiceType?是interface指定的類型。屬性properties 包含了這個服務注冊時的所有屬性。

    A bind callback is invoked when the reference is initially bound to a backing service, and whenever the backing service is replaced by a new backing service.

    當一個引用被綁定到一個服務或這個服務被一個新的服務替換時,將調用綁定回調方法。

    An unbind callback is only invoked when the current backing service is unregistered, and no replacement service is immediately available (i.e., the reference becomes unsatisfied).

    當一個服務被注銷并且沒有可用的服務替換它時,將調用解除綁定的回調方法。

    Bind and unbind callbacks are made synchronously as part of processing an OSGi serviceChanged event for the backing OSGi service, and are invoked on the OSGi thread that delivers the corresponding OSGi ServiceEvent.

    bind和unbind回調方法同步做為 為OSGi后臺服務處理serviceChanged事件過程的一部分,并且在發生相應ServiceEvent事件的線程中執行調用。

    4.2.2 Referencing collections of services

    Sometimes an application needs access not simply to any service meeting some criteria, but to all services meeting some criteria. The matching services may be held in a List or Set (optionally sorted).

    有時一個應用不僅僅只是簡單的使用某個符合匹配標準的服務,而是要使用所有符合匹配標準的服務。這個匹配的服務可能被保存在一個任意類型的List或Set中。

    The difference between using a List and a Set to manage the collection is one of equality. Two or more services published in the registry (and with distinct service ids) may be "equal" to each other, depending on the implementation of equals used by the service implementations. Only one such service will be present in a set, whereas all services returned from the registry will be present in a list.

    是否相等是使用List和Set管理服務集合的區別。2個或多個發布在registry 中的服務(它們有自己的服務ID)可能是一個等同關系(對象是一樣的),這依賴于這個服務是否實現了'equal'方法。只有實現了'equal'方法的服務才會被保存在Set中,否則都會被保存在List中。

    The set and list elements are used to define collections of services with set or list semantics respectively.

    <set>和<list>分別用于定義具有set或list功能的服務集合。

    These elements support the attributes interface, filter, bean-name, cardinality, and context-classloader, with the same semantics as for the reference element. The allowable values for the cardinality attribute are 0..n and 1..n. A cardinality value of 0..n indicates that it is permissible for their to be no matching services. A cardinality value of 1..n indicates that at least one matching service is required at all times. Such a reference is considered a mandatory reference and any exported services from the same bundle (service defined beans) that depend on a mandatory reference will automatically be unregistered when the reference becomes unsatisfied, and reregistered when the reference becomes satisfied again.

    這2個節點支持這些屬性: interface, filter, bean-name, cardinality 和?context-classloader,這些屬性的功能與在<reference>中是一樣的。屬性cardinality 允許的值是 '0..n' 和'1..n',值'0..n' 表示集合中可以沒有匹配的服務。值 '1..n' 表示集合中至少有一個匹配的服務。

    The bean defined by a list element is of type java.util.List. The bean defined by a set element is of type java.util.Set.

    The following example defines a bean of type List that will contain all registered services supporting the EventListener interface:

    下面這個例子定義了一個類型為List的bean,它將會保存所有接口為com.xyz.EventListener的注冊服務。

    <list id="myEventListeners"
    ? interface="com.xyz.EventListener"/>

    The members of the collection defined by the bean are managed dynamically by Spring. As matching services are registered and unregistered in the service registry, the collection membership will be kept up to date. Each member of the collection supports the service interfaces that the corresponding service was registered with and that are visible to the bundle.

    Spring會自動管理這個bean定義的集合的成員,這個集合的成員會被更新,就像在service registry中注冊和注銷一個匹配服務一樣。支持定義的服務接口的集合中所有對象都有一個相應的注冊服務,它們對bundle是可見的。

    It is possible to specify a sorting order using either the comparator-ref attribute, or the nested comparator element. The comparator-ref attribute is used to refer to a named bean implementing java.util.Comparator. The comparator element can be used to define an inline bean. For example:

    可以使用屬性comparator-ref或內嵌一個<comparator >來指定一個排序方式。comparator-ref屬性用來關聯一個實現了java.util.Comparator接口的bean。<comparator> 用于指定一個內部bean。例如:

    <set id="myServices" interface="com.xyz.MyService"
    ? comparator-ref="someComparator"/>

    <list id="myOtherServices"
    ? interface="com.xyz.OtherService">
    ? <comparator>
    ???? <beans:bean class="MyOtherServiceComparator"/>
    ? </comparator>
    </list>

    To sort using a natural ordering instead of an explicit comparator, you can use the natural-ordering element inside of comparator. You need to specify the basis for the natural ordering: based on the service references, following the ServiceReference natural ordering defined in the OSGi Core Specification section 6.1.2.3; or based on the services themselves (in which case the services must be Comparable).

    你可以通過在<comparator>中內嵌一個<natural-ordering>來讓這個集合自己排序,但是你需要指定它基于什么方式排序,OSGi規范中定義的ServiceReference的自然排序方式是基于服務的引用來排序,可以仿照這個排序方式,也可以基于服務本身來排序(這個服務需要實現Comparable接口)。


    <list id="myServices" interface"com.xyz.MyService">
    ? <comparator><natural-ordering basis="services"/></comparator>
    </list>

    <set id="myOtherServices"interface="com.xyz.OtherService">
    ? <comparator><natural-ordering basis="service-references"/></comparator>
    </set>

    When iterating over the collection, the semantics of Iterator are guaranteed to be observed (if hasNext() returns true, then next() will return a service, if hasNext() returns false then next() will throw an exception.). In addition any elements added to the collection during iteration over a sorted collection will only be visible if the iterator has not already passed their sort point.

    當使用Iterator遍歷一個集合時(匹配服務的集合),如果hasNext()返回true,next()將返回一個服務,如果hasNext()返回false,next()將拋出一個exception。另外,在遍歷一個集合的過程中,任何新加入的元素僅僅只是在iterator沒有遍歷到這個新加入元素的排序點時才會被遍歷出來。

    4.2.2.1 Dealing with Service dynamics

    Collection membership is automatically managed as matching services are registered or unregistered. The nested listener element is supported with all of the reference collection beans. The bind callback is invoked whenever a service is added to the collection, and the unbind callback is invoked whenever a service is removed from the collection.

    集合的成員自動做為匹配服務進行注冊和注銷管理。嵌套的<listener>支持所有的引用集合bean。bind回調方法將在一個服務被添加到集合中時調用,unbind方法將在一個服務從集合中除去的時候被調用。

    When iterating over the members of a collection, it is always possible that the service backing a collection member is unregistered after it has been returned from an invocation of Iterator.next(). If an operation is invoked on such a service, a ServiceUnavailableException will be thrown.

    當遍歷一個集合的所有元素時,某個集合成員的服務可能會在通過next()方法返回后被注銷,如果這個服務中的方法被調用,那么將拋出一個ServiceUnavailableException 。

    5.0 Working with Bundles

    The bundle element defines a bean of type org.osgi.framework.Bundle. It provides a simple way to work directly with bundles, including driving their lifecycle. In the simplest case all you need to do is specify the symbolic-name of the bundle you are interested in:

    <bundle>用來定義一個類型為org.osgi.framework.Bundle的bean。它提供了一個簡單的方式直接操作bundle,包括操縱它們的生命周期。在下面的例子中你只需要簡單的為這個bundle指定一個symbolic-name:

    <bundle id="aBundle" symbolic-name="org.xyz.abundle"/>

    The bean aBundle can now be dependency injected into any property of type Bundle.

    現在這個bean可以被注入到任何類型為Bundle的屬性中了。

    The optional location and action attributes provide declarative control over the bundle's lifecycle. The location attribute is used to specify a URL where the bundle jar file artifact can be found. The action attribute specifies the lifecycle operation to be invoked on the bundle object. The supported action values are install, start, update, stop, and uninstall. These actions have the same semantics as the operations of the corresponding names defined on the Bundle interface (see the OSGi Service Platform Core Specification), with the exception that pre-conditions are weakened to allow for example a 'start' action to be specified against a bundle that is not currently installed (it will be installed first).

    可選屬性 location 和 action對這個bundle的聲明周期提供了聲明性的控制。屬性location指定一個可以找到bundle jar包的URL,屬性action指定了在bundle對象中被調用的生命周期操作。

    The following table shows how actions are interpreted for the given Bundle states:

    actionUNINSTALLEDINSTALLED/RESOLVEDACTIVE
    installinstalls the bundleno action taken, bundle already installedno action taken, bundle already installed
    startinstalls and starts the bundlestarts the bundleno action taken, bundle already started
    updateinstalls the bundle and then updates it (`Bundle.update()`)updates the bundleupdates the bundle
    stopno action takenno action takenbundle is stopped
    uninstallno action takenbundle is uninstalledbundle is stopped and then uninstalled

    For example:

    <!-- ensure this bundle is installed and started -->
    <bundle id="aBundle" symbolic-name="org.xyz.abundle"
       location="http://www.xyz.com/bundles/org.xyz.abundle.jar"
       action="start"/>
    

    The 'start-level' attribute can be used to set the start level of the bundle.

    Finally, the bundle element also supports a depends-on attribute which can be used to ensure that the bundle bean is not created before a named bean on which it depends is fully instantiated.

    The samples that ship with the Spring Dynamic Modules project further include support for a virtual-bundle element that can be used to create and install OSGi bundles on the fly from existing artifacts.

    6.0 Compendium Services

    The OSGi Service Platform Service Compendium specification defines a number of additional services that may be supported by OSGi implementations. Spring Dynamic Modules supports an additional "compendium" namespace that provides support for some of these services. By convention, the prefix osgix is used for this namespace.

    <?xml version="1.0" encoding="UTF-8"?>
    <osgi xmlns="http://www.springframework.org/schema/osgi"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:osgix="http://www.springframework.org/schema/osgi-compendium"
       xsi:schemaLocation="http://www.springframework.org/schema/osgi  
            http://www.springframework.org/schema/osgi/spring-osgi.xsd
            http://www.springframework.org/schema/osgi-compendium"
            http://www.springframework.org/schema/osgi/spring-osgi-compendium.xsd"">
    
       <!-- use the OSGi namespace elements directly -->
       <service id="simpleServiceOsgi" ref="simpleService"
           interface="org.xyz.MyService" />
    
       <!-- qualify compendium namespace elements -->
       <osgix:property-placeholder persistent-id="com.xyz.myapp"/>
    
    </osgi>
    

    At present this namespace provides support for the Configuration Admin service. Support for other compendium services may be added in future releases.

    6.1 Configuration Admin

    6.1.1 Property placeholder support

    Spring Dynamic Modules provides support for sourcing bean property values from the OSGi Configuration Administration service. This support is enabled via the property-placeholder element. The property placeholder element provides for replacement of delimited string values (placeholders) in bean property expressions with values sourced from the configuration administration service. The required persistent-id attribute specifies the persistent identifier to be used as the key for the configuration dictionary. The default delimiter for placeholder strings is "${...}".

    Given the declarations:

    <osgix:property-placeholder persistent-id="com.xyz.myapp"/>
    
    <bean id="someBean" class="AClass">
      <property name="timeout" value="${timeout}"/>
    </bean>
    

    Then the timeout property of someBean will be set using the value of the timeout entry in the configuration dictionary registered under the com.xyz.myapp persistent id.

    The placeholder strings are evaluated at the time that the bean is instantiated. Changes to the properties made via Configuration Admin subsequent to the creation of the bean do not result in re-injection of property values. See the managed-service and managed-service-reference elements documented in appendix B if you require this level of integration. The placeholder-prefix and placeholder-suffix attributes can be used to change the delimiter strings used for placeholder values.

    It is possible to specify a default set of property values to be used in the event that the configuration dictionary does not contain an entry for a given key. The defaults-ref attribute can be used to refer to a named bean of Properties or Map type. Instead of referring to an external bean, the default-properties nested element may be used to define an inline set of properties.

    <osgix:property-placeholder persistent-id="com.xyz.myapp">
      <default-properties> 
         <property name="productCategory" value="E792"/>
         <property name="businessUnit" value="811"/> 
      </default-properties>
    </osgix:property-placeholder>
    

    The persistent-id attribute must refer to the persistent-id of an OSGi ManagedService, it is a configuration error to specify a factory persistent id referring to a ManagedServiceFactory.

    6.1.2 Configuration Dictionaries

    Support for directly accessing configuration objects and their associated dictionaries, and for instantiating beans directly from configuration objects is on the Spring Dynamic Modules roadmap. See Appendix A for more information.

    7.0 Testing OSGi based Applications

    By following best practices and using the Spring Dynamic Modules support, your bean classes should be easy to unit test as they will have no hard dependencies on OSGi, and the few OSGi APIs that you may interact with (such as BundleContext) are interface-based and easy to mock. For integration testing (making sure that your application behaves as expected when running under OSGi) some support is needed.

    The Spring Dynamic Modules project provides a test class hierarchy (based on org.springframework.osgi.test.AbstractOsgiTests) that provides support for writing regular JUnit test cases that are then automatically executed in an OSGi environment. The test support:

    • starts the OSGi framework
    • installs and starts any specified bundles required for the test
    • packages the test case itself into a 'virtual bundle' and installs it in the OSGi framework
    • executes the test case inside the OSGi framework
    • shuts down the framework
    • passes the test results back to the originating test case instance that is running outside of OSGi

    By following this sequence it is trivial to write JUnit-based integration tests for OSGi and have them integration into any environment (IDE, build, etc.) that can work with JUnit.

    It is most likely that your test cases will extend AbstractConfigurableBundleCreatorTests. Within your test case, access to the BundleContext is readily available through the inherited getBundleContext() method. From here it is easy to verify service publication, drive bundles through the lifecycle and verify that components react as expected, and so on.

    Here's a simple test that verifies a service has been published as expected:

    public class ServicePublicationTest extends AbstractConfigurableBundleCreatorTests {
    
      protected String[] getBundles() {
        return new String[] {
         "org.xyz.someapp, application-layer, 1.0-SNAPSHOT"
         }
      }
    
      public void testServicePublication() {
         assertNotNull("MyService should be published in tthe registry", 
                       getBundleContext().getServiceReference("org.xyz.MyService"));        
      }
    
    }
    

    All of the bundles required by Spring Dynamic Modules will be installed by default. By overriding the getBundles method you can specify additional application bundles to be installed for the test. In this example we install one bundle, with group id org.xyz.someapp, module id application-layer, and version 1.0-SNAPSHOT. The default behavior of the test support is to look up this dependency in your local maven repository. It is possible to change the lookup strategy using a pluggable ArtifactLocator (see the javadocs for more information). Support for Ivy-based repositories is planned for a future release.

    The test support has been integrated with Equinox, Knopflerfish, and Felix. You can configure the platform used to run the tests in one of two ways:

    1. Set the org.springframework.osgi.test.framework system property to one of equinox, knopflerfish, or felix.
    2. Override the AbstractConfigurableOsgiTests#getPlatformName() operation to return one of the constants: EQUINOX_PLATFORM, KNOPFLERFISH_PLATFORM, or FELIX_PLATFORM.

    By default the test harness will attempt to use Equinox.

    Appendix A: Extensions

    This appendix describes extensions to the core functionality that are shipped with the 1.0 distribution, but are not guaranteed to have backwards compatibility across point releases. We anticipate these features migrating into the core specification in future releases.

    A.1 Annotation-based injection

    The org.springframework.osgi.extensions.annotation bundle that ships with Spring Dynamic Modules provides early access to annotation-based support for injecting references to OSGi services. JDK 1.5 or above is required to use this feature.

    Bean class (setter) methods may be annotated with org.springframework.osgi.annotation.ServiceReference. By default the property type of the annotated property is used to look up a service with a matching service interface in the OSGi service registry and inject the result. For example, given the configuration:

    <bean id="annotationDriven" class="MyAnnotationDrivenBeanClass"/>
    

    and the class declaration:

    public class MyAnnotationDrivenBeanClass {
    
      @ServiceReference
      public void setMessageService(MessageService aService) { ... }
    
    }
    

    then a service lookup for services implementing the MessageService interface will be performed, and the best match (using the same algorithm as documented for the reference element) will be injected.

    The ServiceReference annotation class has a number of attributes that can be used to control the service lookup (for example, to specify a filter string) that mirror the options provided by the reference element. See the javadoc for more information.

    Appendix B: Roadmap

    This appendix documents features on the Spring Dynamic Modules roadmap. The design of these features specified here is subject to change.

    B.1 Enhanced Configuration Admin Support

    B.1.1 Managed Services

    It should be possible to easily instantiate a bean from the configuration information stored for a ManagedService, and a set of beans from the configuration information stored for a ManagedServiceFactory. In addition, updates to the configuration information should be propagated to beans created in this way.

    The managed-service element is used to define a bean based on the configuration information stored under a given persistent id. It has two mandatory attributes, class and persistent-id. The persistent-id attribute is used to specify the persistent id to be looked up in the configuration administration service, class indicates the Java class of the bean that will be instantiated.

    A simple declaration of a managed service bean would look as follows:

     <osgix:managed-service id="myService" class="com.xyz.MessageService" 
       persistent-id="com.xyz.messageservice"/>
    

    The properties of the managed-service bean are autowired by name based on the configuration found under the given persistent id. It is possible to declare regular Spring bean property elements within the managed-service declaration. If a property value is defined both in the configuration object stored in the Configuration Admin service, and in a nested property element, then the value from Configuration Admin takes precedence. Property values specified via property elements can therefore be treated as default values to be used if none is available through Configuration Admin.

    It is possible for the configuration data stored in Configuration Admin to be updated once the bean has been created. By default, any updates post-creation will be ignored. To receive configuration updates, the update-strategy attribute can be used with a value of either bean-managed or container-managed.

    The default value of the optional update-strategy attribute is none. If an update strategy of bean-managed is specified then the update-method attribute must also be used to specify the name of a method defined on the bean class that will be invoked if the configuration for the bean is updated. The update method must have one of the following signatures:

    public void anyMethodName(Map properties)
    public void anyMethodName(Map<String,?> properties); // for Java 5
    public void anyMethodName(Dictionary properties);
    

    When an update strategy of container-managed is specified then the container will autowire the bean instance by name based on the new properties received in the update. For container-managed updates, the bean class must provide setter methods for the bean properties that it wishes to have updated. Container-managed updates cannot be used in conjunction with constructor injection. Before proceeding to autowire based on the new property values, a lock is taken on the bean instance. This lock is released once autowiring has completed. A class may therefore synchronize its service methods or otherwise lock on the bean instance in order to have atomic update semantics.

    B.1.2 Managed Service Factories

    The managed-service-factory element is similar to the managed-service element, but instead defines a set of beans, one instance for each configuration stored under the given factory pid. It has two mandatory attributes, factory-pid and class.

    A simple managed-service-factory declaration would look as follows:

    <osgix:managed-service-factory id="someId" factory-pid="org.xzy.services" 
               class="MyServiceClass"/>
    

    This declaration results in the creation of zero or more beans, one bean for each configuration registered under the given factory pid. The beans will have synthetic names generated by appending "-" followed by the persistent id of the configuration object as returned by Configuration Admin, to the value of the id attribute used in the declaration of the managed-service-factory. For example, someId-config.admin.generated.pid.

    Over time new configuration objects may be added under the factory pid. A new bean instance is automatically instantiated whenever a new configuration object is created. If a configuration object stored under the factory pid is deleted, then the corresponding bean instance will be disposed (this includes driving the DisposableBean callback if the bean implements DisposableBean). The option destroy-method attribute of the managed-service-factory element may be used to specify a destroy callback to be invoked on the bean instance. Such a method must have a signature:

    public void anyMethodName();
    

    It is also possible for the configuration of an existing bean to be updated. The same update-strategy and update-method attributes are available as for the managed-service element and with the same semantics (though obviously only the bean instance whose configuration has been updated in Configuration Admin will actually be updated). The same client-locking semantics also apply when using the container-managed update strategy

    B.1.3 Direct access to configuration data

    If you need to work directly with the configuration data stored under a given persistent id or factory persistent id, the easiest way to do this is to register a service that implements either the ManagedService or ManagedServiceFactory interface and specify the pid that you are interested in as a service property. For example:

    <service interface="org.osgi.service.cm.ManagedService" ref="MyManagedService">
      <service-properties>
        <entry key="service.pid" value="my.managed.service.pid"/>
      </service-properties>
    </service>
    
    <bean id="myManagedService" class="com.xyz.MyManagedService"/>
    

    and where the class MyManagedService implements org.osgi.service.cm.ManagedService.

    B.1.4 Publishing configuration administration properties with exported services

    We intend to provide support for automatic publication of service properties sourced from the Configuration Admin service under a given persistent id. This support has yet to be designed but may look as follows:

    <service ref="toBeExported" interface="SomeInterface">
       <osgix:config-properties persistent-id="pid"/>
    </service>
    

    Issues to be considered are scoping of a subset of properties to be published (public/private), and automatic updates to published service properties if the value is updated via config admin.

    Note that named properties can easily be published as service properties already without this support, simply by using the property-placeholder support.

    B.2 Access to Service References for Collections

    The current specification does not provide for access to the ServiceReference objects for services in a managed collection (i.e. obtained via a set or list declaration). A future release of Spring Dynamic Modules will provide an easy means of gaining access to these references.

    B.3 Start level integration

    A future release of Spring Dynamic Modules may offer the following additional guarantee with respect to application context creation and start levels:

    Application context creation happens asynchronously. However, the extender bundle does guarantee that the creation of all application contexts for bundles at start level n will be complete before the creation of any application context at start level m, where m > n. Care must therefore be taken not to introduce any mandatory dependencies on services exported by bundles with higher start levels or a deadlock will be introduced.

    In a similar vein, when shutting down the extender bundle, application contexts at start level m will be shut down before application contexts at start level n, where m > n.

    B.4 Web application support

    A key part of the roadmap for the next release of Spring Dynamic Modules is built-in support for building web applications out of OSGi bundles. This will be supported using both an HttpService provided by a bundle installed into the running OSGi framework, and also by embedding an OSGi container inside an existing servlet container. Pioneering work has been done by Martin Lippert, Bernd Kolb, and Gerd Wutherich amongst others

    B.5 ORM support

    Care needs to be taken when using JPA or Hibernate under OSGi as the persistence engines must have visibility of the persistent types and mapping files. The Spring Dynamic Modules project will be investigating an extension model to make managing this easier when persistent configuration is split across several bundles. See Peter Krien's blog entry on the topic for an insight into the issues.

    Appendix C: Spring Dynamic Modules Schema

    To be completed - will import schema once we have finalised and updated it following review. Existing .xsd file needs to be tidied up and have improved documentation.

    Appendix D: Acknowledgments

    Thanks to Peter Kriens, Jeff McAffer, Richard S. Hall, Andy Piper, Hal Hildebrand, Glyn Normington, Martin Lippert, Gerd Wuetherich, Bill Gallagher, BJ Hargrave, and Olivier Gruber for their contributions in the development of this specification.=

    posted on 2007-10-10 16:42 Phrancol Yang 閱讀(6962) 評論(1)  編輯  收藏 所屬分類: OSGI

    FeedBack:
    # Internet Promotion 2009-05-18 03:32 Internet Promotion
    Badly need your help. People fail forward to success.
    I am from Mexico and too bad know English, tell me right I wrote the following sentence: "Seo members area - seo product reviews resources directory.Beginner and comprehensive guides to seo, link."

    Thanks :o. Nikita.  回復  更多評論
      
    主站蜘蛛池模板: 两个人日本WWW免费版| 亚洲乱码国产一区三区| 久艹视频在线免费观看| 亚洲aⅴ天堂av天堂无码麻豆| 亚洲AV综合色区无码一区| 国产成人在线观看免费网站| 久久aⅴ免费观看| 一个人看的www免费在线视频| 亚洲欧美成人一区二区三区| 亚洲第一成年人网站| 老司机亚洲精品影院在线观看 | 亚洲一区二区三区丝袜| 亚洲av之男人的天堂网站| 一本色道久久88亚洲综合| 中文字幕无线码中文字幕免费| 亚洲av成人中文无码专区| 亚洲av乱码一区二区三区| 久久久亚洲精品视频| 国产亚洲精品资源在线26u| 亚洲精品国产高清嫩草影院| 曰批全过程免费视频网址| 伊人久久大香线蕉免费视频| eeuss影院免费92242部| 国产亚洲精品欧洲在线观看| 亚洲国产精品成人AV在线| 亚洲欧美国产欧美色欲| 亚洲人成电影院在线观看 | 免免费国产AAAAA片| 91免费国产自产地址入| 最近中文字幕mv免费高清视频8| 久久精品成人免费看| 国产麻豆一精品一AV一免费| 爽爽爽爽爽爽爽成人免费观看| 精品国产免费一区二区三区| 久久成人永久免费播放| 国产性生大片免费观看性| 最近免费字幕中文大全| 久久精品视频免费| 亚洲美女视频免费| 成人无码区免费视频观看| 免费的涩涩视频在线播放|