I´m currently developing an E4 RCP Application and I have the following problem: I have an Part that isn´t visible at the opening of the application (toBeRendered="false" visible="false"). When a button klick on another Part happens, I do the following:

MPart s = partService.findPart("S");
if (s != null) {
s.setToBeRendered(true);
s.setVisible(true);
partService.activate(s); }

This works well. So if the user opens the Part (s) a Composite is created on that Part via a class and in this class I have dependency Injection:

public class S {
    ....
    @Focus
    public void focusGained() {
        ...
        MyComposite m = new MyComposite(parent, SWT.NONE);
        ...
    }
}



public class MyComposite extends Composite {

    @Named("list")
    private HashMap<String, Ex> myMap;

    public MyComposite(Composite parent, int style) {
            super(parent, style);
            myMap.get("key");
        }
}

But I get a NullPointerException at myMap.get("key"); so the Injection does not work. It works on another Part, that is created before this Composite is created so I don´t understand why this Injection does not work.

May someone help me please?

有帮助吗?

解决方案

Injection is only done on objects that the application model knows about. You are creating MyComposite yourself so injection is not done.

You can do the injection yourself with something like:

MyComposite m = new MyComposite(parent, SWT.NONE);

ContextInjectionFactory.inject(m, context);

Note: this will not do injection in the constructor, use a @PostConstruct method.

In any case field injection is not done until after the constructor has run, so your constructor code will never run with injection.

Update: You also only have @Named on the field, you need @Inject as well.

So your class needs to look like:

public class MyComposite extends Composite {

  @Named("list")
  @Inject
  private HashMap<String, Ex> myMap;

  public MyComposite(Composite parent, int style) {
        super(parent, style);
  }

  @PostConstruct
  void postConstruct() {
        myMap.get("key");
  }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top