【发布时间】:2014-05-19 13:50:43
【问题描述】:
我阅读了一些带有基本示例的 spring 教程,但我对如何正确连接事情有点困惑。
问题是,我想使用应用程序上下文来提取单例控制器引用,但我阅读了其他一些主题,即除非绝对必要,否则不应直接访问应用程序上下文。我想我应该使用构造函数来实例化我想要的引用,但是这里的一切对我来说都很模糊。
我有带有几个 fxml 文件的 javafx 应用程序。我有一个主 fxml,另一个在 main 中动态加载。
我将使用简化代码,例如两个 fxml 控制器,MainController.java(用于主 fxml)和 ContentController.java(用于内容 fxml)
这个想法是内容 fxml 具有 TabPane,而主 fxml 具有在 ContentController 上的 TabPane 中打开新选项卡的按钮。
我目前正在做这样的事情
豆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>
主控制器:
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();
}
}
内容控制器:
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”。
【问题讨论】:
标签: java spring spring-mvc dependency-injection javafx