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.
com.packtpub.e4.application
package called StringService
with a @Creatable
annotation, and a process()
method that takes a String
and returns an upper-case version:import org.eclipse.e4.core.di.annotations.Creatable; @Creatable public class SimpleService { public String process(String string) { return string.toUpperCase(); } }
StringService
to the Rainbow
class:@Inject private StringService stringService;
public void selectionChanged(SelectionChangedEvent event) { IStructuredSelection sel = (IStructuredSelection) event.getSelection(); Object colour = sel.getFirstElement(); broker.post("rainbow/colour", stringService.process(colour.toString())); }
By denoting 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 a state that should be shared by multiple callers, register an OSGi service instead, or use a singleton service injected in the context.