I am working on a JavaFX application and I would like to integrate Spring functionality with it. Currently the code compiles without any error, but when I request service la
You have created a SpringFxmlLoader
but you are not using it. You want
SpringFxmlLoader loader = new SpringFxmlLoader();
Parent root = (Parent) loader.load(getClass().getResource("login.fxml").toExternalForm());
instead of using the FXMLLoader
directly.
I would actually write the SpringFxmlLoader
differently, so that it matched the standard FXMLLoader
API a little more closely:
public class SpringFxmlLoader {
private static final ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);
public <T> T load(URL url) {
try {
FXMLLoader loader = new FXMLLoader(url);
loader.setControllerFactory(applicationContext::getBean);
return loader.load();
} catch (IOException ioException) {
throw new RuntimeException(ioException);
}
}
}
Then your start method looks like:
SpringFxmlLoader loader = new SpringFxmlLoader();
Parent root = loader.load(getClass().getResource("login.fxml"));
You might need to tinker with the exact path to get things right, depending on your setup.