如何在JavaFX控制器中使用Guice? [英] How can i use Guice in JavaFX controllers?
问题描述
我有一个JavaFX应用程序,我想介绍Guice,因为我的Code
现在充满了factorys,仅用于测试目的。
I have a JavaFX application where I would like to introduce Guice because my Code is full of factorys right now, only for the purpose of testing.
我有一个用例,其中我有一个特定视图的控制器类。
这个控制器类有一个viewmodel,我通过控制器类的构造函数
将模型传递给viewmodel。
I have one use case where i have a controller class of a certain view. This controller class has a viewmodel and I pass the model to the viewmodel via the constructor of the controller class.
在控制器类中我有一个提供编辑/保存/删除操作的contactservice对象。
截至目前,我有一个该对象的接口,并提供一个实现和一个模拟。这个对象可以通过Factory.getInstance()方法检索。
In the controller class I have a contactservice object that provides the edit/save/delete operations. As of now I have an interface of that object and provide an implementation and a Mock. This object can be retrieved by a Factory.getInstance() method.
我想做的是这样的:
public class NewContactController implements Initializable {
// ------------------------------------------------------------------------
// to inject by guice
// ------------------------------------------------------------------------
private ContactService contactService;
@Inject
public void setContactService(ContactService srv) {
this.contactService = srv;
}
// edit window
public NewContactController(Contact c) {
this.viewModel = new NewContactViewModel(c);
}
// new window
public NewContactController() {
this.viewModel = new NewContactViewModel();
}
@FXML
void onSave(ActionEvent event) {
//do work like edit a contcat,
contactService.editContact(viewModel.getModelToSave());
}
@Override
public void initialize(URL location, ResourceBundle resources) {
// bind to viewmodel---------------------------------------------------
}
}
我怎样才能实现这个目标?做那样的事情是个好主意吗?
在我寻找解决方案的过程中,我找到了 fx-guice 和类似的框架但是如何我能把这两个结合起来吗?
特别是如何让这些字段被注入并自己实例化控制器或者至少给它一些构造函数args?
How can I achive this? Is it a good a idea to do something like that? While I was searching for a solution I found fx-guice and similar frameworks but how can i combine these two? Specially how can I let this fields be injected AND instanciate the controller myself or at least give it some constructor args?
推荐答案
<我不使用Guice,但最简单的方法似乎只是在 FXMLLoader
上使用控制器工厂。您可以创建一个控制器工厂,指示 FXMLLoader
使用Guice初始化您的控制器:
I don't use Guice, but the simplest approach would appear to be just to use a controller factory on the FXMLLoader
. You can create a controller factory that instructs the FXMLLoader
to use Guice to initialize your controllers:
final Injector injector = Guice.createInjector(...);
FXMLLoader loader = new FXMLLoader(getClass().getResource(...));
loader.setControllerFactory(new Callback<Class<?>, Object>() {
@Override
public Object call(Class<?> type) {
return injector.getInstance(type);
}
});
// In Java 8, replace the above with
// loader.setControllerFactory(injector::getInstance);
Parent root = loader.<Parent>load();
这篇关于如何在JavaFX控制器中使用Guice?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!