I am trying to use JavaFX and Spring together. I am using Spring Boot, in particular.
My issue is that I have both Spring autowired fields and JavaFX "autowired" fields in the FXML controller.
I put a breakpoint in the constructor controller and it is actually being invoked twice: one by Spring, which autowires @Autowired fields only, one by JavaFX, which initialize @FXML fields only.
Here's my main code:
@SpringBootApplication
public class MySpringAndJavaFXApp extends AbstractJavaFXAndSpringApplication {
@Override
public void start(Stage window) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("/fxml/home.fxml"));
window.setTitle("My Title");
window.setScene(new Scene(root, 500, 300));
window.show();
}
public static void main(String[] args) {
launchApp(MySpringAndJavaFXApp.class, args);
}
}
Here's the class I am extending:
public abstract class JavaFXAndSpringApplication extends Application {
protected static void launchApp(Class<? extends JavaFXAndSpringApplication> classePrincipaleJavaFX, String[] args) {
launch(classePrincipaleJavaFX,args);
}
private ConfigurableApplicationContext applicationContext;
@Override
public void init() throws Exception {
applicationContext = SpringApplication.run(getClass());
applicationContext.getAutowireCapableBeanFactory().autowireBean(this);
}
@Override
public void stop() throws Exception {
super.stop();
applicationContext.close();
}
}
An example of a class being Spring-managed and JavaFX-managed:
@Component
public class MixedController {
@FXML
private TextField aTextField;
@Autowired
private MyService myService; // MyService is a @Component
public MixedController() {
System.out.println("I am here"); // debugger goes twice here
}
}
How I can easily fix my issue? I attempted using a custom FXML loader (e.g. JavaFX and Spring - beans doesn't Autowire). However, if I load the home.fxml file with such loader, I get an error on the data provider (i.e. Spring is not getting my database configuration correctly) and I would prefer another approach.