如何注入“运行时”依赖项像登录用户那样在应用程序启动时不可用? [英] How to inject a "runtime" dependency like a logged in user which is not available at application boot time?

查看:131
本文介绍了如何注入“运行时”依赖项像登录用户那样在应用程序启动时不可用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是没有得到这个:



我在我的Java GWT应用程序中使用杜松子酒做DI。登录屏幕集成到完整的应用程序窗口中。在用户登录后,我想将用户对象注入到其他类中,例如我创建的GUI Presenters,因此我相信我具有某种运行时相关性。如何做到这一点?



我能想到的一个解决方案就像:

  class Presenter {
@Inject
Presenter(LoggedInUserFactory userFactory){
User user = userFactory.getLoggedInUser();
}
}

class LoggedInUserFactoryImpl {
public static User user;
用户getLoggedInUser(){
返回用户;






$ b

所以,当用户成功登录后,我有对象我在 LoggedInUserFactory 中设置了静态属性,但只有在用户之后创建了 Presenter 已登录的情况并非如此。



或者我应该使用全局静态注册表吗?我只是不喜欢在我的类中使用静态依赖关系的想法。



任何输入都将非常感谢。

解决方案

使用 EventBus 在用户登录时激发事件。



如果您绝对必须使用DI,并且需要用户的演示者才能使用,直到用非空用户正确初始化后才能使用,则可以将您的调用推迟到 GWT.create(MyGinjector.class) code>直到用户登录后。然后,您的应用程序中会有两个这样的调用:一个用于登录代码路径,另一个用于应用程序的其余部分。


I'm just not getting this:

I use Gin in my java GWT app to do DI. The login screen is integrated into the full application window. After the user has logged in I want to inject the user object into other classes like GUI Presenters which I create, so I have some sort of runtime dependency I believe. How do i do that?

One solution I can think of is sth like:

class Presenter {
  @Inject
  Presenter(LoggedInUserFactory userFactory) {
     User user = userFactory.getLoggedInUser();
  }
}

class LoggedInUserFactoryImpl {
  public static User user;
  User getLoggedInUser() {
    return user;
  }
}

So, when the user is successfully logged in and I have the object i set the static property in LoggedInUserFactory, but this will only work if the Presenter is created after the user has logged in which is not the case.

Or should I use a global static registry? I just don't like the idea of having static dependencies in my classes.

Any input is greatly appreciated.

解决方案

Instead of bending DI over backwards to supply the User, use an EventBus to fire an event when the user logs in.

If you absolutely must use DI for this and the presenters that require the User aren't used until properly initialized with a non-null User you can defer your call to GWT.create(MyGinjector.class) until after the User is logged in. You would then have two such calls in your application: one for the login code path and a second for the rest of the application.

这篇关于如何注入“运行时”依赖项像登录用户那样在应用程序启动时不可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆