用Gin进行现场级注射

时间:2012-05-02 12:47:51

标签: java dependency-injection guice gin

我正在尝试进行字段级注入,因此当我的控制器被实例化时,我不必传递“模型”,例如,

UserController controller = new UserController(/*No need to pass models here*/);

但是我的应用程序抛出NullPointerException,这里是我的代码:

UserController.java

    public class UserController implements Controller {
        @Inject private UserModel model;
        public UserController() {
          model.doSomething(); // NullPointerException
        }
    }

ClientGinModule.java

public class ClientGinModule extends AbstractGinModule {
    @Override
    protected void configure() {
        bind(UserModel.class).in(Singleton.class);
    }
}

可能是什么问题?

2 个答案:

答案 0 :(得分:1)

使用In Guice

UserController controller = injector.getInstance(UserController.class);

在杜松子酒中使用:

// Declare a method returning a UserController on your interface extending Ginjector
public UserController getUserController();

// When you need the controller, just call:
injector.getUserController();

获得完全注入的控制器。

答案 1 :(得分:0)

当构造函数仍在运行时,您的model字段将为null。在UserController对象完全创建之后,它将由GIN注入。在这里GWT GIN Field Level Injection你可以找到很好的解释。