JavaFX : Integrating Spring framework with JavaFX app(Incorrect configuration)

前端 未结 1 1508
滥情空心
滥情空心 2021-01-17 07:16

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

相关标签:
1条回答
  • 2021-01-17 07:49

    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.

    0 讨论(0)
提交回复
热议问题