2017-12-04 1 views
0

私はSpringの設定を読み込むためにAnnotationConfigApplicationContextを使います。新しいウィンドウでのSpringインジェクション(FXML)

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()); 
} 

と、これは今、私はFXMLLoaderを経由して、新たなステージ(TestController.fxml)にこのキュータインスタンスを注入したいと思い、私のApplicationConfig

@Configuration 
@ComponentScan 
public class ApplicationConfig { 

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

です。それをどうすれば実現できますか?

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(); 
    } 
} 

すべてのサポートをよろしくお願いいたします。ありがとう!

+0

を行うことができますので、TestControllerは、Spring管理されますあなたがここに明確にすることはできます:あなたが行うことができ、あなたのメインコントローラにように、アプリケーションのコンテキスト自体は、そのようなオブジェクトのですか?あなたは「executorインスタンスを新しいステージに注入する」と言ったとき、あなたは本当に何を意味しますか? 'TestController.fxml'の読み込みに関連するコントローラーにそれを挿入することを意味しますか? (実際にステージに注入することはできません。ステージは事前定義されたクラスであり、エグゼキュータのフィールドはありません)。そして、 'showNewWindow()'のコードはどこにありますか?これは 'main.fxml'のコントローラにありますか? –

+0

はい** showNewWindow()**はmain.fxmlのコントローラにあります。要点は、** ApplicationConfig **を新しいウィンドウに再度登録すると、Executorの新しいインスタンスが作成されますが、私の目標は両方のウィンドウに対して同じExecutorインスタンスを使用することです。希望が助けてくれる! – mitso

答えて

1

"よく知られたオブジェクト"をスプリングマネージドBeanに注入できます。

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(); 
     } 
    } 

    // ... 

} 

今、あなたは、単に

public class TestController { 

    @Autowired 
    private Executor executor ; 

    // ... 

} 
関連する問題