Guice-场注入返回null

时间:2018-08-18 18:42:25

标签: java guice

所以我要做的是将在A中创建的MyGame实例注入到PlayScreen中。到目前为止,这是我的代码:

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
    }
}

但是在render()中的方法PlayScreen中,批处理结果为空。

但是,如果在MyGame中使用injector.getInstance(A.class)一切正常,那么我不会得到null

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

我解决了。正如chrylis所说,我不得不使用构造函数注入而不是字段注入。这是新代码:

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保持不变。