Skip to content

Commit 707cdf4

Browse files
committed
ServiceHelper: load EventService more aggressively
Whenever we have @eventhandler annotated methods, we need an EventService to be loaded as a dependency. Otherwise, even if the EventService is loaded later, those event handlers will not be properly registered with it, since at the time registration was attempted, the EventService was not yet loaded and hence null. This change obviates the need for DefaultEventService being set to an absurdly high priority, as explained at: imagej/ImageJ@b9abe17
1 parent fc28421 commit 707cdf4

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

src/main/java/org/scijava/service/ServiceHelper.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
import org.scijava.AbstractContextual;
4242
import org.scijava.Context;
4343
import org.scijava.Optional;
44+
import org.scijava.event.EventHandler;
4445
import org.scijava.event.EventService;
4546
import org.scijava.log.LogService;
4647
import org.scijava.log.StderrLogService;
@@ -305,6 +306,11 @@ private <S extends Service> S createServiceRecursively(final Class<S> c)
305306
final Double priority = classPoolMap.get(c);
306307
if (priority != null) service.setPriority(priority);
307308

309+
// NB: If there are any @EventHandler annotated methods, we treat the
310+
// EventService as a required dependency, _unless_ there is also an
311+
// EventService field annotated with @Parameter(required = false).
312+
boolean eventServiceRequired = true;
313+
308314
// populate service parameters
309315
final List<Field> fields =
310316
ClassUtils.getAnnotatedFields(c, Parameter.class);
@@ -332,10 +338,18 @@ private <S extends Service> S createServiceRecursively(final Class<S> c)
332338
// recursively obtain needed service
333339
final boolean required = f.getAnnotation(Parameter.class).required();
334340
s = loadService(serviceType, required);
341+
// NB: Remember when there is an optional EventService parameter.
342+
if (s instanceof EventService) eventServiceRequired = required;
335343
}
336344
ClassUtils.setValue(f, service, s);
337345
}
338346

347+
// check for event handlers
348+
if (!ClassUtils.getAnnotatedMethods(c, EventHandler.class).isEmpty()) {
349+
// NB: There are @EventHandler methods; we need an EventService.
350+
loadService(EventService.class, eventServiceRequired);
351+
}
352+
339353
service.initialize();
340354
service.registerEventHandlers();
341355
return service;

0 commit comments

Comments
 (0)