我试图将对象注入到我自己的类(OpenProjectItemHandler
)中,如下所示。但是注入的对象(eventBroker
)为空。我们如何注入物体?
public class ProjectExplorerPart {
protected TreeViewer viewer;
//@Inject IEventBroker eventBroker;
@PostConstruct
public void createComposite(Composite parent) {
//...
viewer.addDoubleClickListener(new OpenProjectItemHandler());
//...
}
}
public class OpenProjectItemHandler implements IDoubleClickListener {
@Inject IEventBroker eventBroker;
@Override
public void doubleClick(DoubleClickEvent event) {
//...
//IEclipseContext eclipseContext = E4Workbench.getServiceContext();
//eventBroker = eclipseContext.get(IEventBroker.class);
eventBroker.send("ta/project_explorer/open_item", Collections.EMPTY_LIST);
}
}
}
最佳答案
使用new
创建的对象不会被注入。您需要使用ContextInjectionFactory.make
创建对象。
public class ProjectExplorerPart {
protected TreeViewer viewer;
@PostConstruct
public void createComposite(Composite parent, IEclipseContext context) {
//...
OpenProjectItemHandler handler
= ContextInjectionFactory.make(OpenProjectItemHandler.class, context);
viewer.addDoubleClickListener(handler);
//...
}
}