Hello其他程序员,
我最近开始研究OSGi项目。我试图使用Declarative Services来习惯OSGi服务。我创建了一个接口包(A),一个实现此接口的包(B)和一个使用该服务的包(C)。到现在为止还挺好。但是当我尝试创建一个实现另一个接口(D)的包时,我发现我无法使用bundle(A)提供的服务。
所以我有4个捆绑包:
为什么我不能从B组中消耗服务E?
捆绑A
package liqueurplant.osgi.silo.driver.api;
import org.osgi.annotation.versioning.ProviderType;
@ProviderType
public interface SiloDriverIf {
void openDriver();
void closeDriver();
}
捆绑B
package liqueurplant.osgi.silo.driver;
import liqueurplant.osgi.silo.controller.api.SiloCtrlIf;
import liqueurplant.osgi.silo.driver.api.SiloDriverIf;
import org.osgi.service.component.annotations.*;
@Component
public class SimpleSiloDriver implements SiloDriverIf {
private SiloCtrlIf siloCtrl;
@Activate
public void activate() {
System.out.println("Driver activated.");
}
@Deactivate
public void deactivate() {
siloCtrl.put2EventQueue("High lever reached");
}
@Override
public void openDriver() {
}
@Override
public void closeDriver() {
}
@Reference(
name = "siloCtrl.service",
service = SiloCtrlIf.class,
/* Cardinality (Whether the bundle works with or without service.
// Mandatory: mandatory and unary 1..1
// At least one: mandatory and multiple 1..n
// Multiple: optional and multiple 0..n
// Optional: optional and unary 0..1
//*/
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetSiloCtrlIf"
)
protected void setSiloCtrlIf(SiloCtrlIf siloCtrl){
System.out.println("Binding silo controller service");
this.siloCtrl = siloCtrl;
}
protected void unsetSiloCtrlIf(SiloCtrlIf siloCtrl){
System.out.println("Unbinding silo controller service.");
this.siloCtrl = null;
}
}
捆绑D
package liqueurplant.osgi.silo.controller;
import liqueurplant.osgi.silo.controller.api.SiloCtrlIf;
import org.osgi.service.component.annotations.*;
import java.util.concurrent.ArrayBlockingQueue;
@Component
public class SimpleSiloCtrl implements SiloCtrlIf, Runnable {
private ArrayBlockingQueue<String> eventQueue;
public SimpleSiloCtrl() {
eventQueue = new ArrayBlockingQueue<String>(20);
}
@Activate
public void activate() {
System.out.println("Silo controller activated.");
}
@Override
public void put2EventQueue(String event) {
try {
eventQueue.put(event);
System.out.println(eventQueue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while(true){
if(!eventQueue.isEmpty()){
try {
System.out.println(eventQueue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
捆绑E
package liqueurplant.osgi.silo.controller.api;
import org.osgi.annotation.versioning.ProviderType;
@ProviderType
public interface SiloCtrlIf {
void put2EventQueue(String event);
}
当我尝试运行代码时,Bundle B上的@Activate方法不起作用,而且服务siloCtrl.service没有绑定。任何帮助,将不胜感激。 提前谢谢!