OSGI Blueprint入门之五

     reference-list除了可以用setter的方式注入OSGI service外,还可以用listener的方法来实现OSGI service的注入。
<?xml version="1.0" encoding="UTF-8"?>
<blueprint
xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd"
default-timeout="0">

<bean id="coders" class="com.ponder.coders">
</bean>
<!-- 为以上bean定义一个引用列表,将所有com.ponder.ICoder服务都通过bindICoder注入进来 -->
<reference-list id="coderExtender" interface="com.ponder.ICoder" availability="optional">
<reference-listener bind-method="bindICoder" unbind-method="unbindICoder" ref="coders">
</reference-listener>
</reference-list>
<!-- bean通过使用引用列表里的服务,对外提供com.ponder.ICodeService服务,这个bean就类似于一个"扩展点" -->
<service id="CoderService" ref="coders" interface="com.ponder.ICodeService">

</service>
</blueprint>


    这种方法就是通过bean里定义由reference-listener子节点的属性bind-method和unbind-method指定的两个方法来注入或撤走服务的引用。这两个方法都带一个com.ponder.ICoder的参数,也就是将要被注入或撤走的那个服务引用。当多个服务被注入(或撤走)时,bind-method(或unbind-method)会被调用多次。这种方式给予你更大的控制自由度。

    另外,reference-list还支持availability属性,可取“optional”和“mandatory”两个选项之一。
     optional代表引用的服务可以为0个,即使引用的服务不存在,也不影响引用它的那个bean,blueprint的应用组装依然能够顺利完成。
     而mandatory则要求引用的服务至少存在1个,被引用的服务必须在超时时间内最少存在1个可用,否则这个bundle的blueprint状态将在超时后变成“fail”,应用的组装将失败,无法对外提供服务。

    最后,reference-list节点也可以和reference节点那样用filter属性来过滤引用的服务。

猜你喜欢

转载自killko.iteye.com/blog/1782596