Separate JavaFX loading from the Neitzel injection container

This commit is contained in:
2026-11-26 16:01:19 +01:00
parent efda8c2d14
commit 20249f5790
106 changed files with 1428 additions and 674 deletions
+64
View File
@@ -0,0 +1,64 @@
# Neitzel DI adapter for FX
The adapter is available in the separated `1.0.7-SNAPSHOT` development
checkout. Install it with `./mvnw -pl fx-injection -am install` from the
NeitzelLib root, using JDK 25 and the same local Maven repository as your
application.
```xml
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>fx-injection</artifactId>
<version>1.0.7-SNAPSHOT</version>
</dependency>
```
Use the same version for all NeitzelLib modules. The adapter resolves `fx`,
`injection` and its scanner dependencies. Applications with their own
`ViewDependencies` can depend on `fx` directly.
Import the adapter from `de.neitzel.fx.injection`, the container from
`de.neitzel.injection` and the loader and Model context from
`de.neitzel.fx.view`.
```java
var services = new ApplicationContext(MyApplication.class);
var dependencies = new NeitzelViewDependencies(services, Set.of(AddressForm.class, VisitRow.class));
var models = new ViewModelContext();
var view = ViewLoader.loadWithDependencies(fxml, model, dependencies, models);
stage.setScene(new Scene(view.getRoot()));
stage.addEventHandler(WindowEvent.WINDOW_HIDDEN, event -> models.close());
```
The registration set contains the exact FXML Component classes, including
those used by Repeat and Table. The adapter asks the context for a fresh
controller or Component and gives FX the corresponding release action.
The release action closes UI instances that implement `AutoCloseable`.
Converters and Localizer come from the context's ordinary lookup. The adapter
reports a missing service as an empty result and propagates lookup or
creation errors. The application owns the context and its shared services.
The JPMS module name is `de.neitzel.fx.injection`. Named applications
keep the package access needed by FXML and Neitzel's package scanner.
Declare `requires de.neitzel.fx.injection` for the adapter and `requires fx` and
`requires injection` for their directly imported types. The Neitzel package
scanner still needs access to its scanned packages in named applications.
## Migrate an existing FX application
Use `ViewLoader.loadWithDependencies(..., dependencies, models)`,
`ViewLoader.loadComponentWithDependencies(..., dependencies, models)`,
and `FxFixture.loadWithDependencies(..., dependencies)` for the new
FX artifacts. Replace the previous public `ApplicationContext` loader
calls and recompile. Retain the Model context with its window or
dockable and close it when that owner ends. Each View load gets its own
controller and Components. If a row previously called a cached controller,
inject the shared action it needs. The [Person Desk](../fx-example/README.md)
does this with `VisitActions`.
A Designer provider on the new artifacts returns the configured adapter
from `PreviewSession.context()` and declares `ViewDependencies` as its
context type. Existing providers returning `ApplicationContext` continue to
run with compatible older FX artifacts such as 1.0.6. Consumers of the standalone
[Neitzel injection container](../injection/README.md) can keep using its
existing API.
+54
View File
@@ -0,0 +1,54 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.7-SNAPSHOT</version>
</parent>
<artifactId>fx-injection</artifactId>
<dependencies>
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>fx</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>injection</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>fx-test</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifestEntries>
<Automatic-Module-Name>de.neitzel.fx.injection</Automatic-Module-Name>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemPropertyVariables>
<glass.platform>Headless</glass.platform>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,53 @@
package de.neitzel.fx.injection;
import de.neitzel.fx.view.ViewDependencies;
import de.neitzel.fx.view.ViewObject;
import de.neitzel.injection.ApplicationContext;
import de.neitzel.injection.MissingComponentException;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
/** Connects managed FX Views to an application-owned Neitzel injection context. */
public record NeitzelViewDependencies(ApplicationContext context, Set<Class<?>> components)
implements ViewDependencies {
/** Creates an adapter with the concrete classes used as FXML Components and rows. */
public NeitzelViewDependencies {
Objects.requireNonNull(context, "Application context");
components = Set.copyOf(components);
}
@Override
public boolean isComponent(Class<?> type) {
return components.contains(type);
}
@Override
public <T> Optional<T> findService(Class<T> type) {
try {
return Optional.of(context.getComponent(type));
} catch (MissingComponentException missing) {
if (missing.getComponentType() == type) return Optional.empty();
throw missing;
}
}
@Override
public <T> ViewObject<T> createViewObject(Class<T> type) {
T instance = context.createComponent(type);
return new ViewObject<>(instance, () -> release(instance));
}
private static void release(Object instance) {
if (instance instanceof AutoCloseable closeable) {
try {
closeable.close();
} catch (RuntimeException failure) {
throw failure;
} catch (Exception failure) {
throw new IllegalStateException("Could not close " + instance.getClass().getName(), failure);
}
}
}
}
@@ -0,0 +1,126 @@
package de.neitzel.fx.injection;
import de.neitzel.fx.i18n.Localizer;
import de.neitzel.fx.injection.fixture.Card;
import de.neitzel.fx.injection.fixture.Controller;
import de.neitzel.fx.injection.fixture.Entry;
import de.neitzel.fx.injection.fixture.Lifecycle;
import de.neitzel.fx.test.FxFixture;
import de.neitzel.fx.test.FxTest;
import de.neitzel.fx.view.ViewLoader;
import de.neitzel.fx.view.ViewModelContext;
import de.neitzel.injection.ApplicationContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.VBox;
import lombok.Getter;
import lombok.Setter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
@FxTest
class NeitzelViewDependenciesTest {
@Getter
@Setter
public static final class Model {
private String name = "Ada";
private List<Entry> entries = new ArrayList<>(List.of(new Entry()));
}
@Test
void loadsRepeatTableAndStandaloneComponentWithOneApplicationContext(FxFixture fx) throws Exception {
fx.run(() -> {
var context = new ApplicationContext(Controller.class);
var lifecycle = context.getComponent(Lifecycle.class);
context.addSingleton(Localizer.class, new Localizer(Locale.ENGLISH, Locale.ENGLISH,
new Localizer.Catalog(Controller.class, "View")));
var dependencies = new NeitzelViewDependencies(context, Set.of(Card.class));
var cached = context.getComponent(Card.class);
assertSame(cached, context.getComponent(VBox.class));
assertFalse(dependencies.isComponent(VBox.class));
try (var models = new ViewModelContext()) {
var model = new Model();
var fxml = Controller.class.getResource("View.fxml");
var first = ViewLoader.loadWithDependencies(fxml, model, dependencies, models);
var second = ViewLoader.loadWithDependencies(fxml, new Model(), dependencies, models);
assertEquals(VBox.class, first.getRoot().getClass());
var caption = (Label) first.getRoot().lookup("#caption");
assertEquals("[Ada]", caption.getText());
assertEquals("Localized", caption.getAccessibleText());
var controller = (Controller) caption.getUserData();
var other = (Controller) second.getRoot().lookup("#caption").getUserData();
assertNotSame(controller, other);
assertSame(lifecycle, controller.getLifecycle());
assertSame(lifecycle, other.getLifecycle());
var embedded = (Card) first.getRoot().lookup("#card");
var repeated = (Card) ((VBox) first.getRoot().lookup("#repeat")).getChildren().getFirst();
var table = first.getRoot().lookup("#table");
var rows = (VBox) ((ScrollPane) table.lookup(".table-scroll")).getContent();
var row = (Card) rows.getChildren().getFirst();
assertNotSame(cached, embedded);
assertNotSame(embedded, repeated);
assertNotSame(repeated, row);
model.getEntries().clear();
assertEquals(1, lifecycle.closeCount(repeated));
assertEquals(1, lifecycle.closeCount(row));
var separate = ViewLoader.loadComponentWithDependencies(Card.class, new Entry(), dependencies, models);
assertEquals("Ada", ((Label) separate.getRoot().lookup("#name")).getText());
separate.close();
assertEquals(1, lifecycle.closeCount(separate.getRoot()));
first.close();
first.close();
assertEquals(1, lifecycle.closeCount(embedded));
assertEquals(1, lifecycle.closeCount(controller));
assertEquals(0, lifecycle.closeCount(other));
assertSame(cached, context.getComponent(Card.class));
}
});
}
@Test
void rollsBackAndDistinguishesMissingServicesFromOverrides(FxFixture fx) throws Exception {
fx.run(() -> {
var failedLookup = new IllegalArgumentException("Lookup override failed");
var context = new ApplicationContext(Controller.class) {
@Override
public <T> T getComponent(Class<? extends T> type) {
if (type == String.class) return type.cast("override");
if (type == Integer.class) throw failedLookup;
return super.getComponent(type);
}
};
var dependencies = new NeitzelViewDependencies(context, Set.of(Card.class));
assertTrue(dependencies.findService(Localizer.class).isEmpty());
assertEquals("override", dependencies.findService(String.class).orElseThrow());
assertSame(failedLookup, assertThrows(IllegalArgumentException.class,
() -> dependencies.findService(Integer.class)));
var acquired = new ArrayList<>();
var tracking = new de.neitzel.fx.view.ViewDependencies() {
public boolean isComponent(Class<?> type) { return dependencies.isComponent(type); }
public <T> java.util.Optional<T> findService(Class<T> type) {
return dependencies.findService(type);
}
public <T> de.neitzel.fx.view.ViewObject<T> createViewObject(Class<T> type) {
var found = dependencies.createViewObject(type);
acquired.add(found.instance());
return found;
}
};
try (var models = new ViewModelContext()) {
assertThrows(IllegalStateException.class, () -> ViewLoader.loadWithDependencies(
Controller.class.getResource("Invalid.fxml"), new Model(), tracking, models));
}
var lifecycle = context.getComponent(Lifecycle.class);
assertEquals(2, acquired.size());
assertTrue(acquired.stream().allMatch(value -> lifecycle.closeCount(value) == 1));
});
}
}
@@ -0,0 +1,28 @@
package de.neitzel.fx.injection.fixture;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.layout.VBox;
@Singleton
public final class Card extends VBox implements AutoCloseable {
private final Lifecycle lifecycle;
private final ObjectProperty<Entry> model = new SimpleObjectProperty<>(this, "model");
@Inject
public Card(Lifecycle lifecycle) {
this.lifecycle = lifecycle;
lifecycle.opened(this);
}
public ObjectProperty<Entry> modelProperty() { return model; }
public Entry getModel() { return model.get(); }
public void setModel(Entry entry) { model.set(entry); }
@Override
public void close() { lifecycle.closed(this); }
}
@@ -0,0 +1,32 @@
package de.neitzel.fx.injection.fixture;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
import javafx.scene.control.Label;
import javafx.fxml.FXML;
import lombok.Getter;
@Singleton
public final class Controller implements AutoCloseable {
@Getter
private final Lifecycle lifecycle;
@FXML
private Label caption;
@Inject
public Controller(Lifecycle lifecycle) {
this.lifecycle = lifecycle;
lifecycle.opened(this);
}
@FXML
private void initialize() {
caption.setUserData(this);
}
@Override
public void close() {
lifecycle.closed(this);
}
}
@@ -0,0 +1,12 @@
package de.neitzel.fx.injection.fixture;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@RequiredArgsConstructor
public final class Entry {
private String name = "Ada";
}
@@ -0,0 +1,13 @@
package de.neitzel.fx.injection.fixture;
import de.neitzel.fx.view.Converter;
import jakarta.inject.Singleton;
@Singleton
public final class FormatName implements Converter {
@Override
public Object toControlValue(Object value) { return "[" + value + "]"; }
@Override
public Object toAttributeValue(Object value) { return value; }
}
@@ -0,0 +1,16 @@
package de.neitzel.fx.injection.fixture;
import jakarta.inject.Singleton;
import java.util.IdentityHashMap;
import java.util.Map;
@Singleton
public final class Lifecycle {
private final Map<Object, Integer> counts = new IdentityHashMap<>();
public void opened(Object instance) { counts.put(instance, 0); }
public void closed(Object instance) { counts.computeIfPresent(instance, (key, count) -> count + 1); }
public int closeCount(Object instance) { return counts.get(instance); }
}
@@ -0,0 +1,10 @@
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.DirectBinding?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<fx:root type="javafx.scene.layout.VBox" xmlns:fx="http://javafx.com/fxml/1">
<fx:define>
<BindingList><DirectBinding control="name" property="text" path="name" direction="view"/></BindingList>
</fx:define>
<Label fx:id="name"/>
</fx:root>
@@ -0,0 +1,7 @@
<?import de.neitzel.fx.injection.fixture.Card?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="de.neitzel.fx.injection.fixture.Controller">
<Label fx:id="caption"/>
<Card unknownProperty="fails after acquisition"/>
</VBox>
@@ -0,0 +1,23 @@
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.Column?>
<?import de.neitzel.fx.view.DirectBinding?>
<?import de.neitzel.fx.view.Repeat?>
<?import de.neitzel.fx.view.Table?>
<?import de.neitzel.fx.injection.fixture.Card?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="de.neitzel.fx.injection.fixture.Controller">
<fx:define>
<BindingList>
<DirectBinding control="caption" property="text" path="name" direction="view"
converter="de.neitzel.fx.injection.fixture.FormatName"/>
<Repeat pane="repeat" collection="entries" component="de.neitzel.fx.injection.fixture.Card"/>
</BindingList>
</fx:define>
<Label fx:id="caption" accessibleText="%view.caption"/>
<Card fx:id="card"/>
<VBox fx:id="repeat"/>
<Table fx:id="table" collection="entries" row="de.neitzel.fx.injection.fixture.Card">
<Column header="Name" attribute="name"/>
</Table>
</VBox>
@@ -0,0 +1 @@
view.caption=Localized