2017-12-09 7 views
1

私は、JavaFxクラスと、startメソッドで作成されたstageの参照を必要とするViewStateクラスを持っているとします。どのように私はそのような依存関係をautowireすることができますか? Stage.classには@Componentと注釈されていないので、Springはduch @Beanを検出できません。注釈の付いていないオブジェクトを挿入する方法Springクラス

@SpringBootApplication 
@ComponentScan({"controller","service","dao","javafx.stage.Stage"}) 
@EntityScan(basePackages = {"Model"}) 
@Import({ SpringConfig.class}) 
public class JavaFXandSpringBootTestApplication extends Application{ 

    private ApplicationContext ctx; 

    public static void main(String[] args) { 
     launch(); 
    } 

    @Override 
    public void start(Stage stage) throws Exception { 
    ViewState viewState = ctx.getBean(ViewState.class); 
} 

ViewStateのクラス:

@Componenet 
public class ViewState { 

@Autowired 
private ApplicationContext ctx; 
private Stage stage; 

@Autowired 
public ViewState(Stage stage) 
{ 
    this.stage = stage; 
} 
} 

コンパイラマッサージ:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javafx.stage.Stage' available: expected at least 1 

答えて

2

あなたは、おそらくすべてでこれを行うにはしたくない:あなたのViewStateクラスは、モデルクラスであるように見えるでしょう何らかの種類なので、UI要素への参照を持たないようにしてください(Stageなど)。

しかし、ここでは、ConfigurableApplicationContext.getBeanFactory().registerResolvableDependency(...)を使用して動作する例を示します。

package example; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.context.annotation.Lazy; 
import org.springframework.stereotype.Component; 

import javafx.scene.Scene; 
import javafx.scene.control.Button; 
import javafx.scene.layout.StackPane; 
import javafx.stage.Stage; 

@Component 
@Lazy 
public class View { 

    @Autowired 
    public View(Stage stage) { 
     Button close = new Button("Close"); 
     close.setOnAction(e -> stage.hide()); 
     StackPane root = new StackPane(close); 
     Scene scene = new Scene(root, 400, 400); 
     stage.setScene(scene); 
     stage.show(); 
    } 
} 
package example; 

import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.SpringBootApplication; 
import org.springframework.context.ConfigurableApplicationContext; 

import javafx.application.Application; 
import javafx.stage.Stage; 

@SpringBootApplication 
public class Main extends Application { 

    private ConfigurableApplicationContext ctx ; 

    @Override 
    public void start(Stage primaryStage) { 
     ctx = SpringApplication.run(Main.class); 
     ctx.getBeanFactory().registerResolvableDependency(Stage.class, primaryStage); 
     ctx.getBean(View.class); 
    } 

    @Override 
    public void stop() { 
     ctx.close(); 
    } 

    public static void main(String[] args) { 
     launch(args); 
    } 
} 
:ステージが登録されるまで、あなたが Viewオブジェクトを作成することはできませんから、あなたが View@Lazyをする必要がある、ということに注意してください
関連する問題