How to use Spring with JavaFX ?

2020-05-25 17:54发布

问题:

I am using javaFX with Scene Builder in my project and I have many pages. I want to avoid complexity, that's why I want to use Spring framework.

So please can anyone explain to me in details how to configure JavaFX with spring framework?

回答1:

I searched for Spring and JavaFX integration sample but could not find a good one. So I worked on an example. You can look at this example application. https://gitlab.com/sunkur/SpringJavaFXController

I hope it helps.



回答2:

There are many ways to integrate Spring with JavaFX. Most of the techniques you will find aim at Spring injection of beans on FXML controllers using the API ControllerFactory on FXMLLoader. A more advanced technique can inject Spring prototype beans as JavaFX custom components in your Scene with the API BuilderFactory (I have made tests with that it works pretty well) of FXMLLoader.

Finally, you have been talking about SceneBuilder. There are still some issues with SceneBuilder and Spring is concerned by some. Take a look at this other post about classloaders and SceneBuilder: Classpath resolution with hierarchical custom JavaFx components in Scenebuilder

It is necessary for SceneBuilder to not be aware of Spring injection if possible. You can achieve that by using deferred instanciation of Spring Context (during "start" of your Application): your custom Spring FXMLLoader will only be used at runtime, and you can use a vanilla FXMLLoader when Spring is not started. This way SceneBuilder will not load Spring with its vanilla FXMLLoader and you won't have classpath problems.