我有一個非常簡單的服務提供者和消費者。出於某種原因,我無法解決我的消費者會使用提供商服務的問題。 下面是提供商束源代碼:在卡拉夫的服務狀態不滿意(參考) - 錯誤在哪裏? (OSGi,聲明式服務,註釋)
package test;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
@Component (name = "MyProvider", immediate = true)
public class TestClass implements SimpleMathI {
public TestClass() {
System.out.println("contructing TestClass");
}
@Activate
protected void activate(ComponentContext c, BundleContext b) {
System.out.println("activate testClass ");
}
@Deactivate
protected void deactivate() {
System.out.println("de-activate testClass");
}
@Override
public void doSimpleAdd(int x, int y) {
System.out.println("Result(TestClass): " + (x + y));
}
@Override
public void doSimpleSubstract(int x, int y) {
System.out.println("Result(TestClass): " + (x - y));
}
}
它註冊部件MYPROVIDER和服務test.SimpleMathI(listed in karaf)
這裏是消費者:
如果我不引用服務SimpleMathI,但只有ConfigurationAdmin它工作正常!
package test;
import org.osgi.framework.BundleContext;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
@Component (name = "MyConsumer", immediate = true, configurationPolicy = ConfigurationPolicy.OPTIONAL)
public class TestClass2 {
public TestClass2() {
System.out.println("contructing TestClass2");
}
@Reference (bind = "bind", unbind = "unbind")
ConfigurationAdmin cm; // works
@Reference (bind = "bindSimpleMathI", unbind = "unbindSimpleMathI")
SimpleMathI simpleMath; // does not work, see screenshot
@Activate
protected void activate(ComponentContext c, BundleContext b) {
System.out.println("activate testClass2");
// simpleMath.doSimpleAdd(20, 25);
}
@Deactivate
protected void deactivate() {
System.out.println("de-activate testClass2");
}
protected void bind(ConfigurationAdmin a) {
System.out.println("binding");
}
protected void unbind(ConfigurationAdmin a) {
System.out.println("un-binding");
}
protected void bindSimpleMathI(SimpleMathI a) {
System.out.println("binding!!");
}
protected void unbindSimpleMathI(SimpleMathI a) {
System.out.println("un-binding!!");
}
}
,這裏是在Karaf webconsole輸出。
我用Google搜索了一下,但仍然無法弄清楚我錯過了什麼。奇怪,因爲代碼非常簡單和透明。那麼,我實施了錯誤的提供商還是消費者?
Karaf 4.0.7,沒有阿帕奇菲利克斯使用,純OSGi的R6的聲明式服務
好的,現在我明白了。還注意到大多數人使用三包方式。這確實很有意義。 – neodix