2013-02-12 85 views
0

我正在使用JavaFX 2与Spring框架一起使用,但是注入发生的很晚。我的控制器被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! 
    } 
} 

任何方式让Spring在以前的状态注入statusbarController?我不能让用户必须点击一个按钮来加载我的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(); 
      } 
     } 
    } 
} 

回答

2

,则应该设置的ControllerFactory上FXMLLoader让你负责的创建控制器实例。

+0

谢谢,这解决了问题!记录:有一个例子,例如这里http://koenserneels.blogspot.de/2012/11/javafx-2-with-spring.html(搜索setcontrollerfactory) – 2013-02-12 15:17:00