0

我将 JavaFX 2 与 Spring Framework 结合使用,但是注入发生得很晚。我的控制器由 FXML-Loader 实例化,该控制器的成员变量的 Spring 注入有效,但它工作得太晚了,这意味着在 (1) 中注入尚未发生,而在 (2) 中注入确实发生了:

public class MainController extends AbstractController
{
    @Autowired
    public StatusBarController statusbarController;

    // Implementing Initializable Interface no longer required according to
    // http://docs.oracle.com/javafx/2/fxml_get_started/whats_new2.htm:
    private void initialize() {
        BorderPane borderPane = (BorderPane)getView();        
        borderPane.setBottom(statusbarController.getView()); // (1) null exception!
    }

    // Linked to a button in the view
    public void sayHello() {
        BorderPane borderPane = (BorderPane)getView();        
        borderPane.setBottom(statusbarController.getView()); // (2) works!
    }
}

有什么方法可以让 SpringstatusbarController在更早的状态下注入?我不能让用户必须单击按钮来加载我的 GUI ;-)

我的 AppFactory 是这样的:

@Configuration
public class AppFactory 
{
    @Bean
    public MainController mainController() throws IOException
    {
        return (MainController) loadController("/main.fxml");
    }

    protected Object loadController(String url) throws IOException
    {
        InputStream fxmlStream = null;
        try
        {
            fxmlStream = getClass().getResourceAsStream(url);
            FXMLLoader loader = new FXMLLoader();
            Node view = (Node) loader.load(fxmlStream);
            AbstractController controller = (AbstractController) loader.getController();
            controller.setView(view);
            return controller;            
        }
        finally
        {
            if (fxmlStream != null)
            {
                fxmlStream.close();
            }
        }
    }
}
4

1 回答 1

2

您应该在 FXMLLoader 上设置一个 ControllerFactory,以便您负责创建控制器实例。

于 2013-02-12T13:17:11.250 回答