The OSGi platform defines a LogService
which allows messages to be logged to a central collector. In the E4 platform, an instance of LogService
is available as part of the platform, routing error messages through to the console.
Hello
class and add a private
field LogService logService
.@Inject
annotation to the LogService
field.create
method, add a call to the log service.Hello
class will look like:import javax.inject.Inject; import org.osgi.service.log.LogService; public class Hello { @Inject private LogService logService; @PostConstruct public void create(Composite parent) { label = new Label(parent, SWT.NONE); label.setText("Hello"); logService.log(LogService.LOG_ERROR, "Hello"); } ... }
!ENTRY org.eclipse.e4.ui.workbench 4 0 2016-06-02 13:36:42.381 !MESSAGE Hello
The E4 runtime infrastructure injected the reference into the class when it was constructed. The instance was obtained from the E4 context, which looks through a hierarchy of contexts until it can find an instance that matches the class type. At the root of the context tree, the list of OSGi services is consulted.
If LogService
cannot be found in the context, the part will fail to be created with an error message:
!ENTRY org.eclipse.e4.ui.workbench 4 0 2016-06-02 13:36:42.381 !MESSAGE Unable to create class 'com.packtpub.e4.app.parts.Hello' from bundle '29' !STACK 0 org.eclipse.e4.core.di.InjectionException: Unable to process "Hello.log": no actual value was found for the argument "LogService" at org.eclipse.e4.core.internal.di.InjectorImpl. reportUnresolvedArgument(InjectorImpl.java:394)
To mark that the service is optional (that is, it can be null
), annotate it with @Optional
:
import org.eclipse.e4.core.di.annotations.Optional; public class Hello { @Inject @Optional private LogService log; @PostConstruct public void create(Composite parent) { if (logService != null) { logService.log(LogService.LOG_ERROR, "Hello"); }
Remember that @Optional
annotated fields or parameters have to be guarded against the possibility of being null
.
If a service arrives after instantiation, the service will be injected into the part.
18.191.88.249