当前位置: 动力学知识库 > 问答 > 编程问答 >

java - 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.

It seems like the eclipse guys don't provide a "simple" solution, see: Bug 413147.

Lars Vogel suggest:

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.

But how to do it, i cant find anything about it? Or should i use a ServiceTracker instead?

网友答案:

You use a class extending ExtendedObjectSupplier to provide an implementation of a qualifier annotation for injection. So if your annotation is @MyService you can do:

@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.

More on using ExtendedObjectSupplier here

Update a summary of using 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'

<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

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
  }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: