导入作为单例 bean(具有工厂方法)的 OSGi 服务

Importing a OSGi service that is a singleton bean (that has a factory method)

如何导入作为单例 bean 的导出的 OSGi 服务?

我最终得到如下异常:

Unable to start blueprint container for bundle opaClient
org.osgi.service.blueprint.container.ComponentDefinitionException: Unable to find a matching constructor on class com.opa.gateway.OPAGateway for arguments [] when instantiating bean opaGateway
    at org.apache.aries.blueprint.container.BeanRecipe.getInstance(BeanRecipe.java:336)

My Blueprint xml导出服务的地方如下:

<bean id="opaGateway" class="com.opa.gateway.OPAGateway" factory-method="getInstance"/>
<service ref="opaGateway" interface="com.opa.gateway.IOPAGateway" />

并且该服务在另一个包中被引用如下:

<reference interface="com.opa.gateway.OPAGateway" component-name="opaGateway" availability="mandatory" />

有没有办法直接引用作为 OSGi 服务的单例 bean?

是的,您可以引用作为 OSGi 服务的单例。确保(如@Balazs 所建议的那样)你的 class 有一个没有参数的静态 function/method getInstance()

看看下面的蓝图。希望它能给你一个线索......(如果你需要完整的示例,我可以尝试 post 它。

<bean   id="opaGateway"
        class="org.test.OPAGateway" factory-method="getInstance">
</bean>

<bean id="opaClient"
      class="org.test.client.OPAClient"
        init-method="startup"
        destroy-method="shutdown">
</bean>

<service ref="opaGateway" interface="org.test.IOPAGateway" />


<reference interface="org.test.IOPAGateway" availability="optional">
    <reference-listener bind-method="setOPAGateway"
                    unbind-method="unsetOPAGateway">
        <ref component-id="opaClient"/>
    </reference-listener>
</reference>

  • bean opaGateway (org.test.OPAGateway)。它是 class 实现 org.test.IOPAGateway。它通过静态方法实例化 getInstance():

    public class OPAGateway implements IOPAGateway {
        private static OPAGateway instance = null;
    
        public static OPAGateway getInstance () {
            if(instance == null) {
                instance = new OPAGateway();
            }
            return instance;
        }
    
        // A very simple method...
        @Override
        public String printMessage() {
            return "I AM AN OPAGATEWAY";
        }
    }
    
  • bean: opaClient: 它只是一个消费者或引用 opaGateway 的 class:

    public class OPAClient {
        public void setOPAGateway(IOPAGateway c) {
            if(c != null) {
                System.out.println("Message: " + c.printMessage());
            }
        }
        public void unsetOPAGateway(IOPAGateway c) {
    
        }
    }
    
  • 参考侦听器:使用bind/unbind-method.

  • opaClient 中注入opaGateway 的实例

您可以在此处找到更多信息:http://www.ibm.com/developerworks/library/os-osgiblueprint/