Rpc 服务变量上的 GIN @Inject
我对变量注入的使用有点迷失。
我让这段代码正常工作:
private XXServiceAsync xxServiceAsync;
@Inject
protected IndexViewImpl(EventBus eventBus, XXServiceAsync tableManagementServiceAsync) {
super(eventBus, mapper);
this.xxServiceAsync = xxServiceAsync;
initializeWidgets();
}
使用这段代码,我可以在类中任何需要的地方调用我的 RPC 服务(单击...) 我想通过直接注入变量来清除一些代码;这样做:
@Inject
private XXServiceAsync xxServiceAsync;
protected IndexViewImpl(EventBus eventBus) {
super(eventBus, mapper);
initializeWidgets();
}
这始终使服务保持为 NULL。 我做错了什么吗? GIN 与 rpc 服务的魔力是否意味着要以其他方式完成?
谢谢!
I'm a bit lost with the use of Inject on variable.
I got this code working :
private XXServiceAsync xxServiceAsync;
@Inject
protected IndexViewImpl(EventBus eventBus, XXServiceAsync tableManagementServiceAsync) {
super(eventBus, mapper);
this.xxServiceAsync = xxServiceAsync;
initializeWidgets();
}
With this code, I can call my RPC service wherever I need in the class (On click ...)
I would like to clear a bit the code by injecting direcly in the variable ; doing so :
@Inject
private XXServiceAsync xxServiceAsync;
protected IndexViewImpl(EventBus eventBus) {
super(eventBus, mapper);
initializeWidgets();
}
This always keep the Service to NULL.
Am I doing something wrong ? Is the GIN magic with rpc services meant to be done otherwise?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此时它仍然为 null,因为 Gin(和 Guice,以及其他类似的框架)在构造函数完成运行之前无法分配字段。
考虑一下如果您手动连接代码(请记住,Gin/Guice 会稍微作弊来分配私有字段,调用不可见的方法),这会是什么样子:
如果您在构造函数中需要某些内容,请将其传递到构造函数中。如果您不会立即需要它(例如直到调用 asWidget() 为止),那么使用 @Inject 注释的字段或设置器可能会有所帮助。
It is still null at that point, because Gin (and Guice, and other frameworks like this) cannot assign the fields until the constructor has finished running.
Consider how this would look if you were manually wiring the code (remember that Gin/Guice will cheat a little to assign private fields, call non-visible methods):
If you need something in the constructor, pass it into the constructor. If you wont need it right away (such as until asWidget() is called), then a field or setter annotated with @Inject can be helpful.
如果您有字段级注入,您可以使用空的 @Inject 方法来进行注入后初始化。无参数注入方法将在类上的字段注入完成后运行。
编辑:我之前说过它也在方法注入之后运行,但测试表明情况并非总是如此。
If you have field level injection you can use an empty @Inject method to do your post-inject initialization. The no-arg injected method will be run after field injections on the class are complete.
Edit: I previously stated that it was run after method injection as well, but testing shows that this is not always the case.