I have a JavaFX application where I would like to introduce Guice because my Code is full of factorys right now, only for the purpose of testing.
I have one use case
I don't use Guice, but the simplest approach would appear to be just to use a controller factory on the FXMLLoader
. You can create a controller factory that instructs the FXMLLoader
to use Guice to initialize your controllers:
final Injector injector = Guice.createInjector(...);
FXMLLoader loader = new FXMLLoader(getClass().getResource(...));
loader.setControllerFactory(new Callback<Class<?>, Object>() {
@Override
public Object call(Class<?> type) {
return injector.getInstance(type);
}
});
// In Java 8, replace the above with
// loader.setControllerFactory(injector::getInstance);
Parent root = loader.<Parent>load();
Assuming you (could) instantiate the controller by hand/guice and not from the FXML, you could use https://github.com/google/guice/wiki/AssistedInject if you need to pass any non DIable parameter to the constructor. You would then set the controller manually to the FXMLLoader with .setController(this) and load the FXML file in the constructor of the controller.
Not sure if there are any drawbacks, but this kind of system seems to work for me :)
There's a good DI framework for javaFX called afterburner.fx. Check it out, I think it's the tool you're looking for.
To use JavaFx with Guice :
Code Example MyApp.java
public class MyApp extends Application {
@Override
public void start(Stage primaryStage) throws IOException {
Injector injector = Guice.createInjector(new GuiceModule());
//The FXMLLoader is instantiated the way Google Guice offers - the FXMLLoader instance
// is built in a separated Provider<FXMLLoader> called FXMLLoaderProvider.
FXMLLoader fxmlLoader = injector.getInstance(FXMLLoader.class);
try (InputStream fxmlInputStream = ClassLoader.getSystemResourceAsStream("fxml\\login.fxml")) {
Parent parent = fxmlLoader.load(fxmlInputStream);
primaryStage.setScene(new Scene(parent));
primaryStage.setTitle("Access mini Stock App v1.1");
primaryStage.show();
primaryStage.setOnCloseRequest(e -> {
System.exit(0);
});
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
launch();
}
}
Then FXMLLoaderProvider.java
public class FXMLLoaderProvider implements Provider<FXMLLoader> {
@Inject Injector injector;
@Override
public FXMLLoader get() {
FXMLLoader loader = new FXMLLoader();
loader.setControllerFactory(p -> {
return injector.getInstance(p);
});
return loader;
}
}
Thanks to mr. Pavel Pscheidl who provided us with this smart code at Integrating JavaFX 8 with Guice