如何使用spring依赖注入连接多个fxml控制器?


问题内容

我阅读了一些带有基本示例的spring教程,并且对如何正确地整理内容有些困惑。

麻烦在于,我想使用应用程序上下文来提取单例控制器引用,但是我读过其他一些主题,除非绝对必要,否则不应直接访问应用程序上下文。我想我应该使用构造函数实例化我想要的引用,但是在这里事情对我来说变得很模糊。

我有几个fxml文件的javafx应用程序。我有一个主要的fxml,而其他主要是动态载入到main内部的。

我将使用简化的代码,例如带有两个fxml控制器的 MainController.java (用于主fxml)和
ContentController.java (用于内容fxml)

这个想法是,内容fxml具有TabPane,而主fxml具有按钮,该按钮可在ContentController的TabPane中打开新的标签。

我目前正在做这样的事情

Bean XML:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="contentController"
class="ContentController"
scope="singleton" />
</beans>

MainControler:

public class MainOverlayControler {

ApplicationContext context;

@FXML
private BorderPane borderPane;

@FXML
private void initialize() {
    loadContentHolder();
}
@FXML
private Button btn;

@FXML
private void btnOnAction(ActionEvent evt) {
    ((ContentController)context.getBean("contentController")).openNewContent();
}

private void loadContentHolder() {
    //set app context
    context = new ClassPathXmlApplicationContext("Beans.xml");

    Node fxmlNode;
    FXMLLoader fxmlLoader = new FXMLLoader();
    fxmlLoader.setController(context.getBean("contentController"));

    try {
    fxmlNode = (Node)fxmlLoader.load(getClass().getResource("Content.fxml").openStream());
    borderPane.setCenter(fxmlNode);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

ContentController:

public class ContentController {
@FXML
private TabPane tabPane;

public void openNewContent() {
    Tab newContentTab = new Tab();
    newContentTab.setText("NewTab");
    tabPane.getTabs().add(newContentTab);
    }
}

主班:

public class MainFX extends Application {
@Override
public void start(Stage primaryStage) {
    try {
        FXMLLoader fxmlLoader = new FXMLLoader();
        Parent root = (Parent) fxmlLoader.load(getClass().getResource("main.fxml").openStream());
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.show();
    } catch(Exception e) {
    e.printStackTrace();
    }
public static void main(String[] args) {
    launch(args);
    }
}

问题: 我想知道如何使用构造函数DI做相同的事情,或者如果我误解了这个概念,可以通过其他方法知道。

我还需要能够从多个其他控制器的“ ContentController”的单例实例上调用“ openNewContent”。


问题答案:

阅读有关JavaFX和Spring集成的更多信息。我推荐斯蒂芬·钱Stephen Chin)的系列

基本上,您需要将JavaFX类嵌入到Spring上下文生命周期中,这在链接的文章中有很好的描述。

您还可以在GitHub上检查他的示例项目,在JavaFX
2.1中引入的控制器工厂简化了代码(请在此处检查