Search code examples
springspring-bootjavafxspring-ioc

Spring in a JavaFX application - how to property handle controller as dependency?


I have a JavaFX application that uses spring boot, exactly as described in this blog post:

http://www.greggbolinger.com/let-spring-be-your-javafx-controller-factory/

I am using the FXML loader overriding the controller factory to use spring.

The problem is that Spring loads the controller class marked as @Component on application start or later if marked with @Lazy, but keeps the bean in memory.

If I open a Stage, modify the data, close the stage and open it again, the data is still there (because the controller was kept by spring). It also gets in the way if I open two of the same Stage (window). It shares the same controller, so if I modify one, the other modifies too, and this is not the desired behavior.

How to I properly handle JavaFX controllers with spring?

Thanks!


Solution

  • Mark the controller as having prototype scope, so that a new instance is created on each request:

    @Component
    @Scope(BeanDefinition.SCOPE_PROTOTYPE)
    public class Controller {
        // ...
    }