简体   繁体   English

如何在Eclipse e4中注入服务的多个实例?

[英]How to inject multiple instances of a services in eclipse e4?

Neither @Inject MyService[] services nor @Inject Collection<MyService> works to get multiple instances of the same service. @Inject MyService[] services@Inject Collection<MyService>无法获取同一服务的多个实例。

It seems like the eclipse guys don't provide a "simple" solution, see: Bug 413147 . 似乎月食专家们没有提供“简单”的解决方案,请参阅: Bug 413147

Lars Vogel suggest: Lars Vogel建议:

I think the correct solution for customers desire that functionality is to define an extended object supplier. 我认为针对客户的正确解决方案希望功能是定义扩展的对象供应商。 Currently we have no plan to support the injection of multiple values via DI. 目前,我们尚无计划支持通过DI注入多个值。

But how to do it, i cant find anything about it? 但是,怎么做,我找不到任何东西? Or should i use a ServiceTracker instead? 还是应该改用ServiceTracker?

You use a class extending ExtendedObjectSupplier to provide an implementation of a qualifier annotation for injection. 您可以使用扩展ExtendedObjectSupplier的类来提供用于注入的限定符注释的实现。 So if your annotation is @MyService you can do: 因此,如果您的注释是@MyService ,则可以执行以下操作:

@Inject @MyService
MyService [] services;

The extended object supplier class is responsible for finding the values to be injected. 扩展对象供应商类负责查找要注入的值。 So you might use ServiceTracker in the supplier. 因此,您可以在供应商中使用ServiceTracker

More on using ExtendedObjectSupplier here 有关在此处使用ExtendedObjectSupplier更多信息

Update a summary of using ExtendedObjectSupplier 更新使用ExtendedObjectSupplier的摘要

Create your annotation: 创建您的注释:

@Qualifier
@Documented
@Target({ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyService {   
} 

Create an OSGi service definition for the supplier using 'New Component Definition' 使用“新组件定义”为供应商创建OSGi服务定义

<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" name="greg.music.core.preferenceSettings">
   <implementation class="package.MyServiceObjectSupplier"/>
   <property name="dependency.injection.annotation" type="String" value="package.MyService"/>
   <service>
      <provide interface="org.eclipse.e4.core.di.suppliers.ExtendedObjectSupplier"/>
   </service>
</scr:component>

The MANIFEST.MF should have a reference to this file in Service-Component MANIFEST.MF应该在Service-Component有对此文件的引用

The supplier class looks like: 供应商类别如下:

public class MyServiceObjectSupplier extends ExtendedObjectSupplier
{
  @Override
  public Object get(final IObjectDescriptor descriptor, final IRequestor requestor, final boolean track, final boolean group)
  {
     // TODO return the object to inject
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM