依赖注入在 javafx google juice 中抛出空指针异常

Dependecy injection throws an null pointer exception in javafx google juice

我有以下class

public class InitialSetupWizardData {
   private final SimpleStringProperty licence_type = new SimpleStringProperty(this,"licenceType","");

  public String getLicence_type() {
    return licence_type.get();
  }

  public SimpleStringProperty licence_typeProperty() {
    return licence_type;
  }

  public void setLicence_type(String licence_type) {
    this.licence_type.set(licence_type);
  }
}

现在我想将其注入我的 javafx 控制器。我添加了以下内容

public class Controller implements Initializable {
   @Inject
   InitialSetupWizardData data;

   @Override
   public void initialize(URL location, ResourceBundle resources) {
     data.setLicence_type("Am cool");
   }
}

上面总是在 data.set 处抛出一个空指针异常...我在使用 google juice 库时错过了什么

注入不会自动发生。对于 FXMLLoader 创建的控制器对象,注入不会发生。

要更改此设置,请在加载 fxml 时使用 controllerFactory。以下示例需要 Injector 以正确创建控制器实例的方式设置 class:

Injector injector = ...
FXMLLoader loader = new FXMLLoader(url);
loader.setControllerFactory(injector::getInstance);
Parent parent = loader.load();