Since JavaFX runtime wants to instantiate my Application object and all of my controller objects, how do I inject dependencies into these objects?
If objects were instantiated by a DI framework, like Spring, the framework would wire up all the dependencies. If I was instantiating the objects manually, I would provide the dependencies through constructor parameters. But what do I do in a JavaFX application?
Thanks!
You can specify a controller factory for the
FXMLLoader
. The controller factory is a function that maps the controller class to an object (presumably, but not necessarily, an instance of that class) which will be used as the controller.So if you want Spring to create the controller instances for you, this can be as simple as:
And now the
FXMLLoader
will create controller instances for aClass<?> c
by callingcontext.getBean(c);
.So, e.g., you could have a configuration:
with
If you're not using a DI framework, and you want to do the injection "by hand", you can do so, but it involves using quite a lot of reflection. The following shows how (and will give you an idea of how much ugly work Spring is doing for you!):
and then just do
Finally, you might want to check out afterburner.fx, which is a very lightweight (in all the best ways) JavaFX-specific DI framework. (It uses a convention-over-configuration approach, where you just match FXML file names to controller class names, and optionally CSS file names, and everything just works.)