如何导入Singleton 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?
答案 0 :(得分:1)
是的,您可以引用作为OSGi服务的单例。确保(如@Balazs建议的那样)你的类有一个没有参数的静态函数/方法getInstance()
。
看看下面的蓝图。希望它能为您提供线索...(如果您需要完整的样本,我可以尝试发布它。
<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)。这是一个实现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的消费者或类:
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在opaGateway
中注入opaClient
的实例。
您可以在此处找到更多信息:code