1

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!

Thiago Sayão
  • 2,197
  • 3
  • 27
  • 41

1 Answers1

3

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 {
    // ...
}
James_D
  • 201,275
  • 16
  • 291
  • 322
  • It is now creating a new instance on each request as you explained, but I still cannot load two instances of the stage, it continues to share the controller instance. Will do some more digging. Thanks! – Thiago Sayão Jun 06 '17 at 16:08
  • You are presumably loading the FXML again when you display the new stage...? – James_D Jun 06 '17 at 16:09
  • Yes, I am creating a new instance of the stage and calling stage.showAndWait(). – Thiago Sayão Jun 06 '17 at 16:11
  • @ThiagoSayão If you can't get it to work, create a [MCVE] and post it. – James_D Jun 06 '17 at 16:12
  • Found the problem, the controller had a dependency on a JavaFX Service class that was annotated with @Service. Annotating it with @Scope(BeanDefinition.SCOPE_PROTOTYPE) fixed it. Thank you! – Thiago Sayão Jun 06 '17 at 16:39