我阅读了一些带有基本示例的 spring 教程,但我对如何正确连接事物有点困惑。
问题是,我想使用应用程序上下文来提取单例 Controller 引用,但我在其他一些主题上读到,除非绝对必要,否则不应直接访问应用程序上下文。我想我应该使用构造函数来实例化我想要的引用,但这里的事情对我来说变得很模糊。
我有带有多个 fxml 文件的 javafx 应用程序。我有一个主要的 fxml,其他的在 main 中动态加载。
例如,我将使用带有两个 fxml Controller 的简化代码,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>
主 Controller :
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();
}
}
内容 Controller :
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 或其他方式做同样的事情。
我还需要能够从多个其他 Controller 对“ContentController”的单例实例调用“openNewContent”。
最佳答案
阅读更多有关 JavaFX 和 Spring 集成的内容。我推荐 Stephen Chin 系列
基本上,您需要将 JavaFX 类嵌入到 Spring 上下文生命周期中,链接文章中对此进行了很好的描述。
您还可以在 GitHub 上查看他的示例项目,其中使用 JavaFX 2.1 中引入的 Controller 工厂简化了代码 (check here)
关于java - 如何使用 spring 依赖注入(inject)连接多个 fxml Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22910399/