-->

How to Inject EPartService

2019-02-07 14:22发布

问题:

I am developing e4 application. I want to inject EPartService outside the Part and Handler when i am injecting EPartService then i will get null pointer error

  public class DisplayRuntimePart {
          @Inject  EPartService partService;
          private void displayPart(){
          MPart part=partService.findPart("com.rcpe4.myproject.part.datapart");                   
          mpart.setVisible(true);
          partService.showPart(mpart, PartState.CREATE);   
    }
  }

I am also read this question but till not solve my problem E4 EPartService findPart() throwing java.lang.Null Pointer Exception

Edit I am inject EPartService in Part class. Class URI in Application.e4xml is bundleclass://com.abc.test/com.abc.test.part.MyPart in this class I am write code as follows.

      Class Mypart{ 
          @Inject EPartService prtservice;                  
          @Inject
          public MyPart() {
          } 
          @PostConstruct
          public void postConstruct(Composite parent) {
             parent.setLayout(new  FillLayout(SWT.HORIZONTAL));     
             htmlBrowser = new Browser(parent, SWT.NONE);

         }  
         @PreDestroy
        public void preDestroy() {

        }   
        @Focus
        public void onFocus() {

        }   
        @Persist
        public void save() {

        } 
         public dispalyPart(){  
                MPart mpart=partService.findPart("com.abc.test.part.datapart"); **Here Getting Null Pointer Exception**
                mpart.setVisible(true);
                partService.showPart(mpart, PartState.CREATE);  
        }
   }

回答1:

Eclipse only does direct injection on objects that it 'knows' about - basically objects mentioned in the application model (e4xmi) files or created using something like EPartService.showPart.

If you want to do direct injection on objects that you create then you need to create them using ContextInjectionFactory. For example:

@Inject IEclipseContext context;

...

MyClass myClass = ContextInjectionFactory.make(MyClass.class, context);

you can also do injection on a class created in the normal way with:

ContextInjectionFactory.inject(myClass, context);

(this will not do injection on the constructor).

Note: Since this code is using direct injection you must run it from a class that the Eclipse application model does know about such as a command handler or an MPart.