当我在osgi中使用我的Bundle时,我需要ServiceReference和Service Object。但是,当我按照下面的代码显示时,我的bundle无法再找到bind方法。我做错了什么?
public class AServiceImpl implements AService{
TestService t;
JournalService journalService;
BundleContext context;
ServiceReference testServiceRef;
public void bindTestService(TestService testService, ServiceReference sv) {
t = testService;
testServiceRef = sv;
//this.testServiceRef = testServiceRef;
test.api.TestStaticVariable.getUniqueInstance().add("TEST A");
System.out.println(test.api.TestStaticVariable.getUniqueInstance().toString());
}
public void unbindTestService(TestService testService){
System.out.println("");
if(t.equals(testService)){
t = null;
}
}
public void bindJournalService(JournalService journalService){
this.journalService = journalService;
}
public void unbindJournalService(JournalService journalService){
if(this.journalService.equals(journalService)){
this.journalService = null;
}
}
}
答案 0 :(得分:2)
见https://osgi.org/download/r4v43/osgi.cmpn-4.3.0.pdf的OSGi纲要4.3第112.3.2节。
所以只需使用ServiceReference
并通过组件上下文获取对象,如112.3.2中所述。
答案 1 :(得分:0)
我找到了解决问题的正确方法:
我只使用从activate方法中检索的BundleContext。在那里,我使用的方法:
testServiceRef = context.getServiceReference(TestService.class);
从bind方法中检索TestService。
答案 2 :(得分:0)
您可以简单地使用FrameworkUtil#getBundle获取任何类的捆绑包,从中可以获取BundleContext。然后从BundleContext中获得ServiceReference,最终可以从BundleContext API中get the service instance。
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
public class GetServiceDemo {
public static ResourceResolverFactory getResourceResolverFactory(){
Bundle bundle = FrameworkUtil.getBundle(ResourceResolverFactory.class);
BundleContext bundleContext = bundle.getBundleContext();
ServiceReference<ResourceResolverFactory> resourceResolverFactoryServiceReference = bundleContext.getServiceReference(ResourceResolverFactory.class);
ResourceResolverFactory resourceResolverFactory = bundleContext.getService(resourceResolverFactoryServiceReference);
return resourceResolverFactory;
}
}
ResourceResolverFactory是已注册的服务。