Search code examples
javajavafxguice

Dependecy injection throws an null pointer exception in javafx google juice


I have the following 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);
  }
}

Now i would like to inject this to my javafx controller. I have added the following

public class Controller implements Initializable {
   @Inject
   InitialSetupWizardData data;

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

THe above always throws a null pointer exception at data.set...What am i missing out as am using the google juice library


Solution

  • The injection does not happen automatically. For controller objects FXMLLoader creates, the injection does not happen.

    To change this use a controllerFactory when loading the fxml. The following example requires a Injector that is set up in a way to properly create a instance of the controller class:

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