弹簧注射新窗口(FXML)

时间:2017-12-04 20:57:40

标签: javafx

我使用AnnotationConfigApplicationContext来加载我的弹簧配置。

public class Main extends Application {

private AnnotationConfigApplicationContext applicationContext;

@Override
public void init() throws Exception {
    applicationContext = new AnnotationConfigApplicationContext(ApplicationConfig.class);

}

@Override
public void start(Stage primaryStage) throws Exception{
    FXMLLoader loader = new FXMLLoader(getClass().getResource("/org/test/view/main.fxml"));
    loader.setControllerFactory(applicationContext::getBean);
    Parent root = loader.load();
    primaryStage.show();
    primaryStage.setOnHidden(e -> Platform.exit());
}

这是我的ApplicationConfig

@Configuration
@ComponentScan
public class ApplicationConfig {

@Bean
public Executor executor() {
    return Executors.newCachedThreadPool(r -> {
        Thread t = new Thread(r);
        t.setDaemon(true);
        return t ;
    });
}

现在我想通过FXMLLoader将此Executor实例注入新的Stage(TestController.fxml)。我怎样才能做到这一点?

public void showNewWindow()  {
    try {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/org/test/view/TestController.fxml"));
        Parent root1 = fxmlLoader.load();
        Stage stage = new Stage();            
        stage.setScene(new Scene(root1));
        stage.show();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

非常感谢所有帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

你可以注入"众所周知的物品"进入春季管理的豆类。应用程序上下文本身就是一个这样的对象,所以在你的主控制器中你可以这样做:

public class MainController {

    @Autowired
    private ApplicationContext applicationContext ;

    public void showNewWindow()  {
        try {
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/org/test/view/TestController.fxml"));
            fxmlLoader.setControllerFactory(applicationContext::getBean);
            Parent root1 = fxmlLoader.load();
            Stage stage = new Stage();            
            stage.setScene(new Scene(root1));
            stage.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // ...

}

现在TestController将由春季管理,因此您只需执行

即可
public class TestController {

    @Autowired
    private Executor executor ;

    // ...

}
相关问题