Dependency Injection in JavaFX with Gluon Ignite and Dagger
The Dependency Injection abstraction framework Gluon Ignite creates a common abstraction over several popular dependency injection frameworks like: Spring, Dagger and Guice.
Currently the Gluon page only contains an example which uses Gluon Ignite with Google Guice as Dependency Injection Framework and I wanted to try Dagger instead of it, because it aims to be more minimalistic and faster than other Dependency Injection Frameworks which is very interesting for less powerful devices like mobile and embedded. In addition to that it’s invented by the developers of Google Guice, but with less ways of doing injection stuff.
In the first step you have to add the dagger dependency to your maven pom (or gradle build file):
After that perform a mvn clean and install or do a rightclick and choose: “reload pom” and “clean and build”. Now you can start with integrating it into your JavaFX main application by creating a new field:
The DaggerContext classes comes with the form previously added maven dependency. Its instantiation takes the JavaFX Main class (this) as first argument and a DaggerModule as the second one. This Module has to be created by hand:
When creating DaggerModules the Module class has to be annotated with the @Module annotation and it also has to inject the JavaFX Main class which is MainApp.class in this example.
In case you want to inject FXMLLoader object as well, you have to create a method annotated with @Provices which returns the FXMLLoader instance.
In case of injecting other objects there are two ways to inject them. Either you can add additional provides methods to the dagger module like for example:
Or you can create a standard no-argument Constructor in the SampleController class which is annotated with @Inject like:
If you don’t implement one of this steps, the JavaFX Main class won’t compile, because Dagger uses generated code to inject the respective classes instead of a heavily usage of reflection like other Dependency Frameworks do.
Links and Further Reading
- http://gluonhq.com/open-source/ignite/
- http://square.github.io/dagger/
- https://www.youtube.com/watch?v=hBVJbzAagfs
Gluon Ignite offers a really nice way to integrate different Dependency Frameworks in JavaFX applications. In addition to that it’s really easy to change the respective DI by using Gluon Ignite. Give it a try!
Reference: | Dependency Injection in JavaFX with Gluon Ignite and Dagger from our JCG partner Bennet Schulz at the Java Enterprise Software Development blog. |