【发布时间】:2016-08-28 04:27:12
【问题描述】:
Karaf 引用没有注入引用对象。请参阅我的设置和代码。
版本:apache-karaf-3.0.5
第 1 部分:服务类
服务:
package org.jrb.test;
public interface MyService
{
String echo(String message);
}
package org.jrb.test;
public class MyServiceImpl implements MyService
{
public String echo(String message)
{
return "Echo processed: " + message;
}
}
蓝图:
<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" default-activation="lazy">
<bean id="serviceBean" class="org.jrb.test.MyServiceImpl"/>
<service id="MyService" ref="serviceBean" interface="org.jrb.test.MyService"/>
</blueprint>
我可以在列表中看到我的服务:
onos> 服务:列表 | grep serviceBean
osgi.service.blueprint.compname = serviceBean
第 2 部分:用于测试的消费者类
蓝图
<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" default-activation="lazy">
<reference id="MyService" interface="org.jrb.test.MyService"/>
<bean id="b" class="org.ct.command.AddCommand" activation="eager" >
<property name="serviceBn" ref="MyService" />
</bean>
<command-bundle xmlns="http://karaf.apache.org/xmlns/shell/v1.1.0">
<command>
<action class="org.ct.command.AddCommand"/>
</command>
</command-bundle>
</blueprint>
在 Java 中:
package org.ct.command;
import org.apache.felix.gogo.commands.Action;
import org.apache.felix.gogo.commands.Argument;
import org.apache.felix.gogo.commands.Command;
import org.apache.felix.service.command.CommandSession;
import org.jrb.test.MyService;
@Command(scope = "onos", name = "service-add", description = "Adds a Client")
public class AddCommand implements Action
{
private MyService serviceBn;
public void setServiceBn(MyService serviceBn)
{
this.serviceBn = serviceBn;
}
public MyService getServiceBn()
{
return service;
}
@Override
public Object execute(CommandSession session) throws Exception
{
System.out.println("Executing command add");
if (serviceBn != null) {
System.out.println("serviceBn is not null");
System.out.println(serviceBn.echo("testing....."));
} else {
System.out.println("serviceBn is null !!");
}
}
}
在上面的代码中,如果我运行命令“service-add”,我的serviceBn 总是null。引用没有注入 bean。
我的代码有什么遗漏吗?
【问题讨论】:
-
您的消费者捆绑包是否从与提供者捆绑包相同的导出包中导入服务?
-
我的观察:在 setter 函数 (setServiceBn(MyService serviceBn)) 中,如果我检查,“MyService”不为空。这意味着它在激活该功能期间正在注入。但是在函数 execute() 之后,它变得空了。对此有何建议?
-
也许你以某种方式构建了 AddCommand 的第二个实例。