Time for action – creating a simple service

POJOs can be instantiated and made available in the E4 context, such that they can be injected into other classes or created on demand. This allows an application to be built in a flexible manner without tight coupling between services.

  1. Create a class StringService in the com.packtpub.e4.application package with a @Creatable annotation, and a process method that takes a string and returns an uppercase version:
    import org.eclipse.e4.core.di.annotations.Creatable;
    @Creatable
    public class StringService {
      public String process(String string) {
        return string.toUpperCase();
      }
    }
  2. Add an injectable instance of StringService to the Rainbow class:
    @Inject
    private StringService stringService;
  3. Use the injected stringService to process the color choice before posting the event to the event broker:
    public void selectionChanged(SelectionChangedEvent event) {
      IStructuredSelection sel = (IStructuredSelection)
       event.getSelection();
      Object colour = sel.getFirstElement();
      broker.post("rainbow/color",
        stringService.process(color.toString()));
    }
  4. Run the application. Go to the Rainbow part and select a color; switch back to the Hello part, and the selected color (for example, Red) should be shown, but in upper case, such as RED.

What just happened?

By marking a POJO with @Creatable, when the dependency injection in E4 needs to satisfy a type, it knows that it can create an instance of the class to satisfy the injection demand. It will invoke the default constructor and assign the result to the injected field.

Note that the resulting instance is not stored in the context; as a result, if additional instances are required (either in a separate field in the same part, or in an alternative part), the dependency injection will create new instances for each injection.

Generally, the use of injectable POJOs in this way should be restricted to stateless services. If the service needs state that should be shared by multiple callers, register an OSGi service instead, or use a singleton service injected in the context.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.122.195