【问题标题】:Guice - Field injection returns nullGuice - 字段注入返回 null
【发布时间】:2018-08-18 18:42:24
【问题描述】:

所以我想做的是将MyGame 中创建的A 实例注入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
    }
}

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

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

我做错了什么?

【问题讨论】:

标签: java guice


【解决方案1】:

我解决了。正如 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 保持不变。

【讨论】:

  • 请注意,除非您在多个地方共享同一个 PlayScreen,否则您可能不会比在没有 Guice 的情况下说出 new PlayScreen(a) 获得任何好处。
  • 我实际上在更多地方使用PlayScreen。此外,它不仅需要a,还需要大约 5 个不同的变量,这些变量也必须在整个程序中传递(所以不仅仅是在PlayScreen 中),所以我觉得这是值得的。我之前做的是在整个程序中传递MyGame,这导致一些非常混乱的代码和添加新功能的困难。
  • 你知道为什么你必须通过构造函数而不是字段注入吗?
猜你喜欢
  • 2017-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-13
  • 1970-01-01
  • 2022-06-15
  • 2016-12-03
  • 1970-01-01
相关资源
最近更新 更多