2014-11-24 87 views
1

我有一個e4應用程序通過處理程序調用插件項目。依賴注入 - Eclipse e4應用程序到eclipse插件

public class CTGHandler{ 
    @Execute 
    public void execute(final EPartService partService, final EModelService modelService){ 
     MPart mPart = modelService.createModelElement(MPart.class); 
     mPart.setLabel("CTG"); //$NON-NLS-1$ 
     mPart.setContributionURI("bundleclass://plugin.project.ctg/test.project.ctg.CTG"); 
     partService.showPart(mPart, PartState.ACTIVATE); 

    } 

} 

在插件方面

public class CTG{ 

    private final Composite parent; 
    private Scale scale; 

    @Inject 
    public CTG(Composite parent){ 
     this.parent = parent; 
    } 

    @PostConstruct 
    public void create(){ 
     scale = new Scale(); 
     Axis x = new Axis(scale); 
     .... 
    } 
} 

和規模類看起來如下

public class Scale{ 

    private int x; 

    @Inject 
    public Scale(){ 
     x = 10; 
    } 
} 

問題:我路過scale作爲參數傳遞給軸心國類Axis x = new Axis(scale);

問題:如何在規模對象上使用依賴關係注入,以便使用它可用於Axis類或插件項目中的任何其他類,而不將其作爲變量傳遞給構造函數。我嘗試在CTG.java和Axis.java中添加@Inject private Scale scale,但Axis類沒有得到縮放值。

回答

3

您可以將@Creatable註釋添加到Scale類告訴噴油器來創建一個新的實例在需要時:

@Creatable 
public class Scale 
{ 
    ... 
} 

如果你只想要Scale一個實例添加@Singleton

@Creatable 
@Singleton 
public class Scale 
{ 
    ... 
} 

您也可以使用OSGi服務來創建單例類,或者然後將其注入到AddOn或LifeCycle類中的上下文中。

依賴注入通常只在Eclipse創建的對象上完成。如果你想要做的對象注射創建使用ContextInjectionFactory創建對象:

@Inject 
IEclipseContext context; 

... 

Axis x = ContextInjectionFactory.make(Axis.class, context); 

make另一種版本,您可以添加額外的值:

IEclipseContext staticContext = EclipseContextFactory.create(); 

staticContext.set(Scale.class, scale); 

Axis x = ContextInjectionFactory.make(Axis.class, context, staticContext);