Hypnic Jerk
Hypnic Jerk

Reputation: 1192

Guice NullPointerExceptions

So I am new to Guice and I am continually getting NullPointerExceptions whenever I attempt to use my Injected objects.

I at first thought it was the weird complexity of my program, but I created a very, very simple test program and I still get them. Program is below:

Main.java

public class Main  extends Application{
    public static void main(String[] args) {
        launch(Main.class);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        Injector injector = Guice.createInjector(new BillingModule());

        Parent p = FXMLLoader.load(getClass().getResource("addtest.fxml"));

        primaryStage.setScene(new Scene(p, 100, 100));
        primaryStage.show();
    }
}

BillingModule.java

public class BillingModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(Add.class).to(AddImpl.class);
    }
}

Add interface

public interface Add {
   int add(int a, int b);
}

AddImpl

public class AddImpl implements Add{
    public int add(int a, int b) {
        return a+b;
    }
}

FXML Controller

public class AddTestController {
    @Inject private Add add;
    public void initialize(){}
    @FXML
    private void addTestButton(){
        System.out.println(add.add(1,3));
    }
}

FXML file

<AnchorPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.121" xmlns:fx="http://javafx.com/fxml/1" fx:controller="AddTestController">
   <children>
      <Button mnemonicParsing="false" onAction="#addTestButton" text="Button" />
   </children>
</AnchorPane>

As you can see it is a VERY simple program, and I still can not seem to get this to work.

My goal is to have Add being Injected without having to call injector.getInstance(Add.class), but instead see the @Inject and resolve the dependency itself, which it is not doing.

I feel like I am missing a very basic understanding of why its not working, but it just hasn't revealed itself yet.

Any ideas on what I'm doing wrong and how to fix it?

P.S. I am using Field injection as an example here, I know its not suggested and in my actual program will not be using it.

Upvotes: 0

Views: 133

Answers (1)

fabian
fabian

Reputation: 82461

Guice only injects to classes created using Injector.getInstance. You need to create the controller using this method. You could do this by setting the controllerFactory of FXMLLoader before calling the load method:

Injector injector = Guice.createInjector(new BillingModule());

FXMLLoader loader = new FXMLLoader(getClass().getResource("addtest.fxml"));
loader.setControllerFactory(injector::getInstance);
Parent p = loader.load();

Upvotes: 4

Related Questions