编写可扩展 OSGi 应用程序

如果您正在编写设计为可扩展的 OSGi 应用程序,那么必须以某种方式确保声明服务引用,以便仅供应必需的捆绑软件。

本主题描述可扩展应用程序设计的常见方案,并提供有关如何声明关联的服务引用以确保供应正确的捆绑软件的指导。

方案 1

您的应用程序设计为可由实现特定接口的一个或多个服务来扩展,但是在首次部署应用程序时未实现此类服务。

Define a <reference-list> element in the Blueprint XML file of the client bundle, with the availability attribute set to "optional". 然后,如果此后通过添加包含实现该接口的一个或多个服务的组合捆绑软件来扩展应用程序,那么在更新该应用程序时将部署该组合捆绑软件。

示例

应用程序设计为可由实现 PaymentProvider 接口的一个或多个服务来扩展。 在首次部署该应用程序时未实现此类服务。 在客户机捆绑软件的“蓝图”XML 文件中定义了以下引用列表:
<reference-list id="paymentProviderRef"
   interface="com.myco.providers.PaymentProvider"
   availability="optional" />

方案 2

应用程序设计为可由实现特定接口的一个或多个服务来扩展,在首次部署该应用程序时会将该类服务嵌入到其中。 在客户机捆绑软件的“蓝图”XML 文件中定义以下元素:
  • A <reference> element for the built-in service, with the availability attribute set to "mandatory".
  • A <reference-list> element for the services that will be added later, with the availability attribute set to "optional".
Then use the filter attribute on the <reference> element to distinguish between the two types of service. filter 属性通过引用一个定制服务属性来选择必需的服务,您必须将该服务属性添加到服务捆绑软件的“蓝图”XML 文件中内置服务的注册条目
警告:
不要只定义一个 availability 属性设置为“mandatory”的引用列表。 此配置将导致以下情况:即,在部署应用程序时,除了会供应嵌入应用程序的打算供应的服务,还会供应内部捆绑软件存储库和任何外部捆绑软件存储库中所有匹配的服务。 系统会将包含其他匹配的服务的捆绑软件添加到共享捆绑软件空间,在该位置它们可能会被无意地访问。 availability 属性的缺省值为“mandatory”。

示例

应用程序设计为可由实现 PaymentProvider 接口的一个或多个服务来扩展。 在首次部署应用程序时将一个此类服务 CardSample 嵌入到了应用程序中。

为了区分 CardSample 服务和以后扩展应用程序时添加的服务,在注册 CardSample 服务时,会将名为“type”且值为“built-in”的服务属性添加到 CardSample 服务。 在服务捆绑软件的“蓝图”XML 文件中定义了以下服务注册:
<service id="builtInPaymentProvider" ref="cardSample"
  interface="com.myco.providers.PaymentProvider>
   <service-properties>
      <entry key="type" value="built-in">
   </service-properties>
</service>

<bean id="cardSample" class="com.myco.providers.CardSampleImpl" />

内置服务的服务引用指定了定制服务属性的 filter 属性;这确保了在部署应用程序时,只会部署内置的服务。

在客户机捆绑软件的“蓝图”XML 文件中定义了以下服务引用:
<reference id="builtInPaymentProviderRef"
   interface="com.myco.providers.PaymentProvider"
   availability="mandatory"
   filter="(type=built-in)"/>

<reference-list id="extensionPaymentProviderRef"
   interface="com.myco.providers.PaymentProvider"
   availability="optional" />