用杜松子酒进行场水平注入 [英] Field level injection with Gin
本文介绍了用杜松子酒进行场水平注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试进行字段级注入,因此在实例化控制器时不必传递模型,例如
I'm trying to do field-level injection so I don't have to pass "models" when my controllers are instantiated, like,
UserController controller = new UserController(/*No need to pass models here*/);
但是我的应用程序抛出NullPointerException,这里是我的代码:
However my application throws NullPointerException, here my code:
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);
}
}
可能是什么问题?
推荐答案
在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();
以获得完全注入的控制器。
to get a fully-injected controller.
这篇关于用杜松子酒进行场水平注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文