-1

So what I want to do is inject the instance of A created in MyGame into PlayScreen. Here is my code so far:

class MyGame extends Game {
    public A a;

    public void create() {
        a = new A();
        Injector injector = Guice.createInjector(new GameModule(this));
        setScreen(new PlayScreen());
    }
}


public class GameModule extends AbstractModule {
    MyGame game;

    public GameModule(MyGame game){
        this.game = game;
    }

    @Override protected void configure() {}

    @Provides
    @Singleton
    A getA() {
        return game.a;
    }
}

public class PlayScreen extends Screen {
    @Inject A a;

    public void render() {
        // Using a
    }
}

But in the method render() from PlayScreen, batch comes out as null.

However, if in MyGame I use injector.getInstance(A.class) everything works, I do not get null.

What am I doing wrong?

Luca1152
  • 175
  • 2
  • 11
  • It's essentially the same problem as https://stackoverflow.com/questions/19896870/why-is-my-spring-autowired-field-null/49803576. The best approach is to use constructor injection instead of field injection, which will immediately identify the spots where dependencies are missing. – chrylis -cautiouslyoptimistic- Aug 18 '18 at 18:44
  • That did it, thanks! I will post the answer. – Luca1152 Aug 18 '18 at 18:54
  • Possible duplicate of [Why is my Spring @Autowired field null?](https://stackoverflow.com/questions/19896870/why-is-my-spring-autowired-field-null) – Jan Galinski Aug 19 '18 at 10:10

1 Answers1

0

I solved it. As chrylis said, I had to use constructor injection instead of field injection. Here is the new code:

class MyGame extends Game {
    public A a;

    public void create() {
        a = new A();
        Injector injector = Guice.createInjector(new GameModule(this));
        setScreen(injector.getInstance(PlayScreen.class));
    }
}

@Singleton
public class PlayScreen extends Screen {
    A a;

    @Inject 
    PlayScreen(A a) {
        this.a = a;
    }

    public void render() {
        // Using a
    }
}

GameModule remained the same.

Luca1152
  • 175
  • 2
  • 11
  • Note that unless you're sharing that same `PlayScreen` among several places, you may not gain anything over just saying `new PlayScreen(a)` without Guice. – chrylis -cautiouslyoptimistic- Aug 19 '18 at 05:28
  • I actually use `PlayScreen` in more places. Also, it doesn't need just `a`, it need about 5 different variables that also have to be passed around the whole program (so not just in `PlayScreen`), so I feel it's worth it. What I was doing before was passing `MyGame` around the entire program, which resulted in some really messy code and a difficulty in adding new features. – Luca1152 Aug 19 '18 at 11:19
  • 1
    did you figure out why you had to do via constructor over field injection? – ealeon May 22 '19 at 17:44