我想解决以下问题,并需要建议,什么是最好的解决方案。
我有一个包A,其中定义了一个服务接口X。包B提供X的服务实现,并将实现贡献给工具。A和B使用Google和Peaberry来配置对象的设置。
我可以使用两种可能性来贡献服务实现:
<extension point="A.service.X">
<xservice
...
class="org.ops4j.peaberry.eclipse.GuiceExtensionFactory:B.XImpl"
.../>
</extension>
<extension
point="org.ops4j.peaberry.eclipse.modules">
<module
class="B.XModule">
</module>
</extension>但我需要这样的样板代码:
private List<X> getRegisteredX() {
final List<X> ximpls = new ArrayList<>();
for (final IConfigurationElement e : Platform.getExtensionRegistry().getConfigurationElementsFor( X_EXTENSION_POINT_ID)) {
try {
final Object object = e.createExecutableExtension("class"); //$NON-NLS-1$
if (object instanceof X) {
ximpls.add((X) object);
}
} catch (final CoreException ex) {
// Log
}
}
return ximpls;
}所以我有一些问题:
<?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" name="Ximpl">
<implementation class="some.generic.guiceaware.ServiceFactory:B.Ximpl"/>
<service>
<provide interface="A.X"/>
</service>
</scr:component>总之,我想要一个由Guice生成的服务实现,并且我希望将服务实现简单地注入到使用服务的类中,而不需要大量的样板代码。有谁能解决这个问题吗?
对不起,我想问一下,但是我在网上搜索了很长一段时间,到目前为止我还没有找到解决办法。
谢谢并致以良好的问候,拉尔斯
发布于 2015-02-19 14:39:08
我找到了一个解决方案,但由于我没有找到它,没有经过大量的尝试和思考,我认为我在这里分享它。根据我在帖子中提到的选项,我的解决方案使用了第一个选项,即Eclipse扩展点和扩展。为了在扩展点的上下文中使用Guice,有两个方面需要考虑:
提供由Guice注入器创建的扩展
这里很好地解释了这一点:https://code.google.com/p/peaberry/wiki/GuiceExtensionFactory。我有一句话要说。扩展对象的创建是在GuiceExtensionFactory内部的注入器中完成的,因此它是自己的上下文,需要由作为工厂附加扩展的模块配置。如果您有其他需要,需要自己在包中创建注入器,这可能会成为一个问题。
定义一个扩展点,以便简单地将扩展注入到使用扩展的类中。
首先要做的是像往常一样定义扩展点模式文件。它应该包含必须由扩展实现的接口的引用。
扩展点的id必须连接到由扩展提供的接口,接口由guice/peaberry注入。因此,peaberry提供了一个注释,用于对接口进行注释:
import org.ops4j.peaberry.eclipse.ExtensionBean;
@ExtensionBean("injected.extension.point.id")
public interface InjectedInterface {
...
}在某些网页上,您还可以找到这样的信息:如果id等于接口的限定名,则可以在没有注释的情况下直接找到它,但我没有尝试。
为了启用注入,您必须做两件事来配置Guice注入器创建。
首先,必须将Peaberry的EclipseRegistry对象设置为ServiceRegistry。其次,必须完成扩展实现到提供的服务的绑定。
注入器的创建必须以这样的方式进行:
import org.osgi.framework.BundleContext;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.ops4j.peaberry.eclipse.EclipseRegistry;
import static org.ops4j.peaberry.Peaberry.*;
void initializer() {
Injector injector = Guice.createInjector(osgiModule(context, EclipseRegistry.eclipseRegistry()), new Module() {
binder.bind(iterable(InjectedInterface.class)).toProvider(service(InjectedInterface.class).multiple());
});
}这样就可以简单地注入扩展实现:
private Iterable<InjectedInterface> registeredExtensions;
@Inject
void setSolvers(final Iterable<InjectedInterface> extensions) {
registeredExtensions = extensions;
}按照所描述的方式,可以通过使用Guice的类实现注入扩展,以获得依赖项。
到目前为止,我还没有找到使用osgi服务的解决方案,但是也许有人有想法。
向你问好,拉尔斯
https://stackoverflow.com/questions/28472618
复制相似问题