Spring Framework & JavaFX integrated?

I recently started learning JavaFX.  I have never build a desktop application before and decided to give it a try.

I am a newbie in JavaFX but I’ve been working with Spring framework for quite some time.

I wanted to be able to combine Spring with JavaFX so that I can take advantage of all the goodies of the framework plus the goodies of JavaFX.

Googling a bit about this topic, I ended up in a excellent post from Stephen Chin which you can read here.

Being inspired from that post I decided to dig into Spring and JavaFX, a bit, in order to be able to “annotation” enable JavaFX controllers so that they can be auto detected by Spring and thus auto wired, auto proxied, etc.

I ended up with a piece of code which I would like to share.  It’s not final, it’s not perfect but it serves it’s purpose.  I intend to enrich it as my JavaFX knowledge is accumulated.

No more talking let’s go for the code.

@EnableFXMLControllers({<packages…>})

That’s the annotation to enable FXML Controllers scanning from Spring config classes.  It is very simple as you can see below:

https://gist.github.com/mandekisd/9fa0e09190888fa4273a

What is important in our case is the “@Import” annotation which imports a very important class the FXMLControllerBeanDefinitionRegistrarSupport.

This class is responsible for the class path scanning and the assignment of the controller factory, the class that produces the FXML controller beans.

https://gist.github.com/mandekisd/74b5217128cef18ad41f

Next is the controller factory which instantiates the controllers in the JavaFX style but it also does the auto wiring the Spring style.  This class has to be instantiated as a bean in the Spring context.  For my own convenience, I have created a configuration class (SpringJavaFXConfig which can be found below) and I just include this in my main app config :

https://gist.github.com/mandekisd/201e8e78d095c11335a4

As you can see the above mentioned factory in order to operate needs a special annotation on the FXML controller which is named, what a surprise, FXMLController:

https://gist.github.com/mandekisd/9eb69e3d172c98649d0c

SpringJavaFXConfig as mentioned above:

https://gist.github.com/mandekisd/ff12b1f8aa9beb2a33e0

And last but not least an ExampleController:

https://gist.github.com/mandekisd/2d7d756fc85fb36ad669

SampleConfig class:

https://gist.github.com/mandekisd/6e7a3b57c7b04ad03cf4

 

Leave a Reply