gpt4 book ai didi

java - 将@Inject 与带有 Eclipse4 依赖注入(inject)的 OSGi 服务一起使用

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:14:32 24 4
gpt4 key购买 nike

我有3个插件

  • de.vogella.osgi.quote(定义接口(interface) IQuoteService)
  • de.vogella.osgi.ds.quoteservice(定义实现报价服务)
  • test(我的实际应用)

我正在使用 list 中的服务组件条目将 QuoteService 注册为 OSGi 服务,基本上遵循说明 here .

我正在尝试使用以下代码将此服务注入(inject)到我的应用程序中:

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 , 应该是可以的。

最佳答案

您没有向注入(inject)代码提供 IEclipseContext,因此它无法解析该服务(如果您不提供上下文,则无法回退)。

在 Activator 中,您可以通过以下方式访问 OSGi 服务上下文:

IEclipseContext serviceContext = EclipseContextFactory.getServiceContext(bundleContext);

使用 ContextInjectionFactory 而不是 InjectorFactory:

ContextInjectionFactory.inject(this, serviceContext);

关于java - 将@Inject 与带有 Eclipse4 依赖注入(inject)的 OSGi 服务一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22579637/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com