我有3个插件
de.vogella.osgi.quote
(定义接口IQuoteService)de.vogella.osgi.ds.quoteservice
(定义实施
QuoteService)test
(我的实际申请)我正在使用清单中的服务组件条目将QuoteService
注册为 OSGi 服务,基本上遵循here的说明。
我正在尝试使用此代码将此服务注入我的应用程序中:
package test;
import javax.inject.Inject;
import org.eclipse.e4.core.di.InjectorFactory;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import de.vogella.osgi.quote.IQuoteService;
public class Activator extends AbstractUIPlugin {
@Inject
IQuoteService quoteService;
public static final String PLUGIN_ID = "test"; //$NON-NLS-1$
private static Activator plugin;
public Activator() {
}
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
InjectorFactory.getDefault().inject(this, null);
System.out.println(quoteService.getQuote());
}
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
}
当我运行时,我得到了这个例外:
Caused by: org.eclipse.e4.core.di.InjectionException: Unable to process "Activator.quoteService": no actual value was found for the argument "IQuoteService".
at org.eclipse.e4.core.internal.di.InjectorImpl.reportUnresolvedArgument(InjectorImpl.java:412)
at org.eclipse.e4.core.internal.di.InjectorImpl.resolveRequestorArgs(InjectorImpl.java:403)
at org.eclipse.e4.core.internal.di.InjectorImpl.inject(InjectorImpl.java:108)
at org.eclipse.e4.core.internal.di.InjectorImpl.inject(InjectorImpl.java:84)
at test.Activator.start(Activator.java:45)
我知道我的服务已注册,因为我可以使用以下代码访问它:
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
ServiceReference serviceReference = context.
getServiceReference(IQuoteService.class.getName());
quoteService = (IQuoteService) context.
getService(serviceReference);
//InjectorFactory.getDefault().inject(this, null);
System.out.println(quoteService.getQuote());
}
我正在尝试做什么?根据诸如this之类的某些来源,它应该是可能的。
答案 0 :(得分:4)
您没有向注入代码提供IEclipseContext
,因此无法解析该服务(如果您不提供上下文,则不会出现回退)。
在Activator中,您可以使用以下命令访问OSGi服务上下文:
IEclipseContext serviceContext = EclipseContextFactory.getServiceContext(bundleContext);
使用ContextInjectionFactory
而不是InjectorFactory
:
ContextInjectionFactory.inject(this, serviceContext);