Skip to content

Commit 8c48289

Browse files
ctruedenclaude
andcommitted
scijava-context: declarative dependency injection
@dependency fills in services, the Context and the EventBus, after construction and before Service.initialize, so a dependency is ready by the time initialization runs. An optional dependency (required = false) stays null; a missing required one names the field and the type it wanted. It is deliberately not called @parameter as in SciJava Common. There that annotation meant two unrelated things -- a dependency to inject, and an input to a module -- and the second is now org.scijava.struct's business. Keeping the name would have preserved muscle memory at the price of re-importing the confusion. scijava-context-test injects private fields of a plugin across a real module boundary, which proves both halves of the JPMS claim at once: a qualified `opens` grants the container the deep reflection it needs, and the package remains exported to nobody, so ordinary callers still cannot reach the implementation. Also makes two assertions in PluginDiscoveryTest select plugins by name rather than by position. Adding a third plugin to the test module broke them, which is a fair warning about how they were written. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013gJpzGd3ksbME4CN6Tu2ni
1 parent 6c4337f commit 8c48289

8 files changed

Lines changed: 423 additions & 12 deletions

File tree

‎docs/migration-plan.md‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -549,9 +549,18 @@ No application context required by anything in this phase.
549549
appear. This is the hazard noted above, met first-hand. `pom-scijava`
550550
configuring this for SciJava components would remove the trap for the
551551
people most likely to fall into it.
552-
- Still to do here: declarative field injection through a qualified `opens`,
553-
`@EventHandler` scanning, the one-way legacy bridge, and the core services
554-
themselves.
552+
- **Field injection is done**: `@Dependency` fills in services, the
553+
`Context` and the `EventBus`, after construction and before
554+
`Service.initialize`. It is deliberately not called `@Parameter` as in
555+
SciJava Common, where that annotation meant two unrelated things — a
556+
dependency to inject, and an input to a module — the second of which is
557+
now `org.scijava.struct`'s business.
558+
`scijava-context-test` injects **private** fields of a plugin across a
559+
real module boundary, proving both halves of the earlier claim at once:
560+
the qualified `opens` grants the container deep reflection, and the
561+
package is still exported to nobody.
562+
- Still to do here: `@EventHandler` scanning, the one-way legacy bridge, and
563+
the core services themselves.
555564
- **Dependencies are not constructor arguments.** Constructor injection
556565
would publish every dependency in a signature, so changing an internal
557566
dependency would be an API change and a binary compatibility break unless

‎docs/migration.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,7 @@ A **dropped** row is a successful outcome, not a gap.
111111
| `cache` | `scijava-cache` moves in, keeping `org.scijava.cache` (Phase 2) | planned |
112112
| `thread` | `org.scijava.concurrent` | ported |
113113
| `task` | `org.scijava.progress` | ported |
114+
| `plugin.Parameter` (as dependency injection) | `org.scijava.context.Dependency`. Renamed because `@Parameter` meant both "inject this" and "this is a module input"; the latter is now `org.scijava.struct` | ported |
114115
| `plugin` (`Plugin`, `Attr`, `PluginService`, `PluginInfo`, `PluginIndex`) | `org.scijava.context.Plugin` and `Attr`, discovered via `Context.plugins(Class)`. `PluginInfo` becomes `org.scijava.discovery.Discovery`, which reports class name, metadata and priority without loading the class; `PluginService` and `PluginIndex` are subsumed by `Context.plugins` | ported |
115116
| `plugin` (the `HandlerPlugin`/`WrapperPlugin`/`TypedPlugin`/`SingletonPlugin` hierarchy and their services) | not ported — each user of these inlines the small contract it needs, as `DataHandle` did | dropped |
116117
| `service` | `org.scijava.context`: `Service` (no longer a plugin, and discovered via `ServiceLoader`), with `Context` holding them. `SciJavaService` has no equivalent — a marker is not needed. `ServiceHelper` and `ServiceIndex` are internal to `Context` | ported |
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/*-
2+
* #%L
3+
* Integration tests for the scijava-context library.
4+
* %%
5+
* Copyright (C) 2021 - 2025 SciJava developers.
6+
* %%
7+
* Redistribution and use in source and binary forms, with or without
8+
* modification, are permitted provided that the following conditions are met:
9+
*
10+
* 1. Redistributions of source code must retain the above copyright notice,
11+
* this list of conditions and the following disclaimer.
12+
* 2. Redistributions in binary form must reproduce the above copyright notice,
13+
* this list of conditions and the following disclaimer in the documentation
14+
* and/or other materials provided with the distribution.
15+
*
16+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17+
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18+
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19+
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
20+
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21+
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22+
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23+
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24+
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25+
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26+
* POSSIBILITY OF SUCH DAMAGE.
27+
* #L%
28+
*/
29+
30+
package org.scijava.context.test.impl;
31+
32+
import org.scijava.context.Context;
33+
import org.scijava.context.Dependency;
34+
import org.scijava.context.Plugin;
35+
import org.scijava.context.test.GreeterService;
36+
import org.scijava.context.test.Shouter;
37+
import org.scijava.priority.Priority;
38+
39+
/**
40+
* A plugin with <em>private</em> dependency fields, in a package that is
41+
* opened to the container but exported to nobody.
42+
* <p>
43+
* Injecting these is deep reflection, so it works only because of the
44+
* qualified {@code opens} in this module's descriptor - and it stays
45+
* encapsulated, because {@code opens} is not {@code exports}.
46+
* </p>
47+
*/
48+
@Plugin(type = Shouter.class, name = "injected", priority = Priority.VERY_HIGH)
49+
public class InjectedShouter implements Shouter {
50+
51+
@Dependency
52+
private GreeterService greeter;
53+
54+
@Dependency
55+
private Context context;
56+
57+
@Override
58+
public String shout() {
59+
return greeter.greet().toUpperCase();
60+
}
61+
62+
/** Exposed so the test can check the context was injected too. */
63+
public Context injectedContext() {
64+
return context;
65+
}
66+
}
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
/*-
2+
* #%L
3+
* Integration tests for the scijava-context library.
4+
* %%
5+
* Copyright (C) 2021 - 2025 SciJava developers.
6+
* %%
7+
* Redistribution and use in source and binary forms, with or without
8+
* modification, are permitted provided that the following conditions are met:
9+
*
10+
* 1. Redistributions of source code must retain the above copyright notice,
11+
* this list of conditions and the following disclaimer.
12+
* 2. Redistributions in binary form must reproduce the above copyright notice,
13+
* this list of conditions and the following disclaimer in the documentation
14+
* and/or other materials provided with the distribution.
15+
*
16+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17+
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18+
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19+
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
20+
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21+
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22+
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23+
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24+
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25+
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26+
* POSSIBILITY OF SUCH DAMAGE.
27+
* #L%
28+
*/
29+
30+
package org.scijava.context.test;
31+
32+
import static org.junit.jupiter.api.Assertions.assertEquals;
33+
import static org.junit.jupiter.api.Assertions.assertFalse;
34+
import static org.junit.jupiter.api.Assertions.assertSame;
35+
import static org.junit.jupiter.api.Assertions.assertTrue;
36+
37+
import org.junit.jupiter.api.Test;
38+
import org.scijava.context.Context;
39+
import org.scijava.discovery.Discovery;
40+
41+
/**
42+
* Tests dependency injection across a real module boundary.
43+
* <p>
44+
* Injecting a private field is deep reflection, so this passes only because
45+
* the implementation package is opened to the container - and the package is
46+
* still exported to nobody, so the encapsulation the plugin framework is
47+
* supposed to provide is intact.
48+
* </p>
49+
*
50+
* @author Curtis Rueden
51+
*/
52+
public class InjectionTest {
53+
54+
@Test
55+
public void testPrivateFieldsAreInjectedAcrossModules() {
56+
try (final Context context = Context.create()) {
57+
final Discovery<Shouter> discovery = context.plugins(Shouter.class) //
58+
.stream() //
59+
.filter(d -> "injected".equals(d.attr("name").orElse(null))) //
60+
.findFirst().orElseThrow();
61+
62+
final Shouter shouter = discovery.get();
63+
// The injected service is what makes this work.
64+
assertEquals("HELLO FROM A HIDDEN IMPLEMENTATION", shouter.shout());
65+
}
66+
}
67+
68+
@Test
69+
public void testTheContextInjectsItself() {
70+
try (final Context context = Context.create()) {
71+
final Shouter shouter = context.plugins(Shouter.class).stream() //
72+
.filter(d -> "injected".equals(d.attr("name").orElse(null))) //
73+
.findFirst().orElseThrow().get();
74+
75+
// NB: reached reflectively, since the class itself is not exported.
76+
final Object injected = shouter.getClass().getMethod("injectedContext")
77+
.invoke(shouter);
78+
assertSame(context, injected);
79+
}
80+
catch (final ReflectiveOperationException exc) {
81+
throw new AssertionError(exc);
82+
}
83+
}
84+
85+
/** Injection must not require exporting anything. */
86+
@Test
87+
public void testInjectionDoesNotRequireExporting() {
88+
final Module module = Shouter.class.getModule();
89+
assertTrue(module.isNamed(), "not running on the module path");
90+
assertFalse(module.isExported("org.scijava.context.test.impl"),
91+
"injection must not require the package to be exported");
92+
}
93+
}

‎scijava-context-test/src/test/java/org/scijava/context/test/PluginDiscoveryTest.java‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@
5353
*/
5454
public class PluginDiscoveryTest {
5555

56+
private static final String INJECTED =
57+
"org.scijava.context.test.impl.InjectedShouter";
5658
private static final String LOUD = "org.scijava.context.test.impl.LoudShouter";
5759
private static final String QUIET =
5860
"org.scijava.context.test.impl.QuietShouter";
@@ -64,8 +66,8 @@ public void testPluginsAreDiscovered() {
6466
final List<String> names = context.plugins(Shouter.class).stream() //
6567
.map(Discovery::implClassName) //
6668
.collect(Collectors.toList());
67-
// NB: highest priority first.
68-
assertEquals(List.of(LOUD, QUIET), names);
69+
// NB: highest priority first: VERY_HIGH, HIGH, LOW.
70+
assertEquals(List.of(INJECTED, LOUD, QUIET), names);
6971
}
7072
}
7173

@@ -76,7 +78,11 @@ public void testPluginsAreDiscovered() {
7678
@Test
7779
public void testMetadataWithoutLoadingTheClass() {
7880
try (final Context context = Context.create()) {
79-
final Discovery<Shouter> loud = context.plugins(Shouter.class).get(0);
81+
// NB: select by name rather than position, so that adding a plugin
82+
// elsewhere in this module does not break this test.
83+
final Discovery<Shouter> loud = context.plugins(Shouter.class).stream() //
84+
.filter(d -> LOUD.equals(d.implClassName())) //
85+
.findFirst().orElseThrow();
8086

8187
assertEquals(LOUD, loud.implClassName());
8288
assertEquals("loud", loud.attr("name").orElse(null));

‎scijava-context/src/main/java/org/scijava/context/Context.java‎

Lines changed: 72 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929

3030
package org.scijava.context;
3131

32+
import java.lang.reflect.Field;
3233
import java.util.ArrayList;
3334
import java.util.Collections;
3435
import java.util.Comparator;
@@ -154,6 +155,7 @@ public <S extends Service> Optional<S> optionalService(final Class<S> type) {
154155
// NB: publish before initializing, so that two services depending
155156
// on each other resolve instead of recursing.
156157
byRequestedType.put(type, s);
158+
inject(s);
157159
initialize(s);
158160
// NB: record for disposal only once initialization has finished.
159161
// A service's dependencies finish first, so they land earlier in
@@ -195,6 +197,28 @@ public <P> List<Discovery<P>> plugins(final Class<P> type) {
195197
return plugins;
196198
}
197199

200+
/**
201+
* Fills in the {@link Dependency}-annotated fields of the given object.
202+
* <p>
203+
* Services and plugins the context creates are injected automatically; this
204+
* is for objects it did not create.
205+
* </p>
206+
*
207+
* @param target the object whose dependencies to fill in
208+
* @throws ServiceException if a required dependency is missing, or the
209+
* target's package is not open to this module
210+
*/
211+
public void inject(final Object target) {
212+
if (target == null) throw new NullPointerException("target");
213+
for (Class<?> c = target.getClass(); c != null; c = c.getSuperclass()) {
214+
for (final Field field : c.getDeclaredFields()) {
215+
final Dependency dependency = field.getAnnotation(Dependency.class);
216+
if (dependency == null) continue;
217+
injectField(target, field, dependency);
218+
}
219+
}
220+
}
221+
198222
/** Gets this context's event bus. */
199223
public EventBus events() {
200224
return events;
@@ -257,6 +281,45 @@ public void close() {
257281

258282
// -- Helper methods --
259283

284+
/** Fills in one annotated field. */
285+
private void injectField(final Object target, final Field field,
286+
final Dependency dependency)
287+
{
288+
final Object value;
289+
try {
290+
value = resolve(field.getType());
291+
}
292+
catch (final NoSuchServiceException exc) {
293+
if (!dependency.required()) return;
294+
throw new ServiceException("Cannot satisfy " + target.getClass()
295+
.getName() + "." + field.getName() + ": no service of type " + field
296+
.getType().getName(), exc);
297+
}
298+
try {
299+
// NB: deep reflection, so the target's package must be open to this
300+
// module. `opens` is not `exports`: the package stays invisible to
301+
// ordinary callers.
302+
field.setAccessible(true);
303+
field.set(target, value);
304+
}
305+
catch (final RuntimeException | IllegalAccessException exc) {
306+
throw new ServiceException("Cannot inject " + target.getClass()
307+
.getName() + "." + field.getName() + //
308+
". Does its module declare `opens " + target.getClass()
309+
.getPackageName() + " to org.scijava.context;`?", exc);
310+
}
311+
}
312+
313+
/** Resolves what to inject for a field of the given type. */
314+
private Object resolve(final Class<?> type) {
315+
if (type == Context.class) return this;
316+
if (type == EventBus.class) return events;
317+
if (Service.class.isAssignableFrom(type)) {
318+
return service(type.asSubclass(Service.class));
319+
}
320+
throw new NoSuchServiceException(type);
321+
}
322+
260323
/**
261324
* Builds the index-backed plugin discoverer.
262325
* <p>
@@ -265,13 +328,13 @@ public void close() {
265328
* annotation loads the <em>declared</em> type, never the implementation.
266329
* </p>
267330
*/
268-
private static IndexDiscoverer<Plugin> createPluginDiscoverer() {
331+
private IndexDiscoverer<Plugin> createPluginDiscoverer() {
269332
return new IndexDiscoverer<>(Plugin.class, //
270333
item -> item.annotation().type().getName(), //
271334
item -> attrsOf(item.annotation()), //
272335
item -> item.annotation().priority(), //
273336
Thread.currentThread().getContextClassLoader(), //
274-
Context::instantiate);
337+
this::instantiate);
275338
}
276339

277340
/**
@@ -284,15 +347,18 @@ private static IndexDiscoverer<Plugin> createPluginDiscoverer() {
284347
* packages to {@code org.scijava.context}.
285348
* </p>
286349
*/
287-
private static Object instantiate(final Class<?> type) {
350+
private Object instantiate(final Class<?> type) {
351+
final Object plugin;
288352
try {
289-
return type.getDeclaredConstructor().newInstance();
353+
plugin = type.getDeclaredConstructor().newInstance();
290354
}
291355
catch (final ReflectiveOperationException exc) {
292356
throw new ServiceException("Cannot construct plugin: " + //
293-
type.getName() + ". Does its module open the package to" + //
294-
" org.scijava.context?", exc);
357+
type.getName() + ". Does its module declare `opens " + type
358+
.getPackageName() + " to org.scijava.context;`?", exc);
295359
}
360+
inject(plugin);
361+
return plugin;
296362
}
297363

298364
/** Flattens a plugin's metadata into the discovery's attribute map. */

0 commit comments

Comments
 (0)