FXML Controller类中的依赖项注入失败

时间:2019-01-25 00:27:43

标签: java javafx dependency-injection guice dagger-2

我正在编写JavaFX应用程序,尝试将DI与Dagger / Guice集成,但是在注入FXML Initializable类时遇到问题。基本上,我是从此处复制代码:{{3}}

在主类(App.java)中,注入工作正常。 这是注入失败的类:

public class FXMLController implements Initializable {

    @FXML
    private Label label;

    @Inject
    ConnectionManager connectionManager;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        //do something with connectionManager
    }
}

基本上,发生的是,当我尝试使用匕首注入时,它只是没有打开场景,而当注入guice时,它抛出了“应用程序启动方法中的异常”。

剩余代码:

DaggerModule for dagger version:

@Module(library = true, injects = {App.class, FXMLController.class}, complete = false)
public class DaggerModule {

    @Provides
    FXMLLoader provideFxmlLoader() {
        return new FXMLLoader();
    }

    @Provides
    ConnectionManager provideConnectionManager() {
        return new ConnectionManager();
    }
}

Guice版本的GuiceModule:

public class GuiceModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(ConnectionManager.class);
    }
}

主类:

public class App extends Application {

//    private final DaggerContext context = new DaggerContext(this, () -> Arrays.asList(new DaggerModule()));
    private GuiceContext context = new GuiceContext(this, () -> Arrays.asList(new GuiceModule()));

    @Inject
    public ConnectionManager connectionManager;

    @Inject
    public FXMLLoader loader;

    @Override
    public void start(Stage stage) throws Exception {
        context.init();
        Parent root = (Parent) loader.load(getClass().getResource("scene.fxml"));

        Scene scene = new Scene(root);
        scene.getStylesheets().add(getClass().getResource("styles.css").toExternalForm());

        stage.setOnCloseRequest(e -> Platform.exit());

        stage.setTitle("title");
        stage.setScene(scene);
        stage.show();

        connectionManager.initConnection();

    }

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

    @Override
    public void stop() throws Exception {
        super.stop();
        System.exit(0);
    }
}

任何想法在这里可能是什么问题?

0 个答案:

没有答案