如何在未附加到应用程序模型的类中使用eclipse 4 DI? [英] How to use eclipse 4 DI in classes that are not attached to the application model?

查看:139
本文介绍了如何在未附加到应用程序模型的类中使用eclipse 4 DI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个带声明性服务的OSGI服务,用于注入实现接口的对象。如果我将对象注入附加到应用程序模型(处理程序,部分,....)的类中,它可以正常工作。如果我将它注入一个没有附加到应用程序模型的类中,它总是返回null。

I have created a OSGI service with declarative services to inject an object that implements an interface. If I inject the object in a class that is attached to the application model (handler,part,....) it is working fine. If I inject it in a class that is not attached to the application model it is always returning null.

是否可以在未附加到的类中使用DI应用模型?我查看了vogella教程,但不知怎的,我找不到解决方案。

Is it possible to use DI in classes that are not attached to the application model? I looked in the vogella tutorials but somehow I don't find a solution.

推荐答案

我知道Eclipse 4如何在类中注入对象的三种方式:

I know of three ways of how Eclipse 4 can inject objects in your classes:


  1. 在启动期间,Eclipse运行时会在它实例化的类中查找相关的注释。

  2. 跟踪注入的对象,并将如果更改,则重新注入。

  3. 使用ContextInjectionFactory和IEclipseContext手动触发注入。

您可以使用第三个选项获得所需的内容。 此处是一个代码示例:

What you want may be possible with the third option. Here is a code example:

    ManipulateModelhandler man = new ManipulateModelhandler();

    //inject the context into an object
    //IEclipseContext iEclipseContext was injected into this class
    ContextInjectionFactory.inject(man,iEclipseContext);

    man.execute();

然而问题是;已经需要将IEclipseContext注入到可以访问需要注入的对象的类中。根据必要的注射次数,使用委托可能更有用(可测试性是一个参数)。

The problem is, however; that the IEclipseContext already needs to be injected into a class that can access the object that needs injection. Depending on the number of necessary injections, it might be more useful to use delegation instead (testability would be one argument).

    @Inject
    public void setFoo(Foo foo) {
        //Bar is not attached to the e4 Application Model
        bar.setFoo(foo);
    }

因此,更好的解决方案可能是使用 @ Creatable 注释。
只需注释你的类,并给它一个无参数的构造函数。

Therefore, a better solution is probably using the @Creatable annotation. Simply annotate your class, and give it a no-argument constructor.

   @Creatable
   public class Foo {
       public Foo () {}
   }

使用@Inject on如上述方法中的类型,将让Eclipse实例化并注入它。
缺点是你无法控制对象创建,就像使用ContextInjectionFactory.inject(..)一样。

Using @Inject on that type as in the method above, will let Eclipse instantiate and inject it. The disadvantage is that you cannot control the object creation anymore, as you would with ContextInjectionFactory.inject(..).

这篇关于如何在未附加到应用程序模型的类中使用eclipse 4 DI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆