【问题标题】:Using Guice to inject values that are generated at runtime使用 Guice 注入运行时生成的值
【发布时间】:2015-10-21 08:10:04
【问题描述】:

我有一个 Context 类,它是一个在运行时逐渐填充的键值对。

我想创建需要来自上下文的一些值的对象实例。

例如:

public interface Task
{
    void execute();
}

public interface UiService
{
    void moveToHomePage();
}

public class UiServiceImpl implements UiService
{
    public UiService(@ContexParam("username") String username, @ContexParam("username") String password)
    {
        login(username, password);
    }

    public void navigateToHomePage() {}

    private void login(String username, String password) 
    {
        //do login
    }
}

public class GetUserDetailsTask implements Task
{
    private ContextService context;

    @Inject
    public GetUserDetailsTask(ContextService context)
    {
        this.context = context;
    }

    public void execute()
    {
        Console c = System.console();
        String username = c.readLine("Please enter your username: ");
        String password = c.readLine("Please enter your password: ");
        context.add("username", username);
        context.add("password", password);
    }
}

public class UseUiServiceTask implements Task
{
    private UiService ui;

    @Inject
    public UseUiServiceTask(UiService uiService)

    public void execute()
    {
        ui.moveToHomePage();
    }
}

我希望能够使用 Guice 创建一个 UseUiServiceTask 实例。 我如何做到这一点?

【问题讨论】:

  • 您尝试过 Provider 吗?
  • 如果我做对了,提供者在我的情况下不起作用。你能详细说明一下吗?
  • 我在想stackoverflow.com/a/15493413/4462333 之类的东西,如果它不锻炼,我可能误解了你的问题。您能否对其进行编辑以添加与您的问题相关的更多代码/信息?
  • 我的上下文与 Web 开发无关。把它想象成一个哈希表,当我的应用程序运行时它会增长。我将更新我的问题以澄清。
  • 创建 Foo 但此时 Bar 不存在时会发生什么?

标签: java dependency-injection guice


【解决方案1】:

您的数据就是:数据。不要注入数据,除非它是在您获取模块之前定义的,并且对于应用程序的其余部分是恒定的。

public static void main(String[] args) {
  Console c = System.console();
  String username = c.readLine("Please enter your username: ");
  String password = c.readLine("Please enter your password: ");

  Guice.createInjector(new LoginModule(username, password));
}

如果您希望在注入开始后检索您的数据,则根本不应该尝试注入它。然后你应该做的是在你需要的任何地方注入你的ContextService,和/或调用回调,但我更喜欢回调,因为不必集中维护数据。

public class LoginRequestor {
  String username, password;
  public void requestCredentials() {
    Console c = System.console();
    username = c.readLine("Please enter your username: ");
    password = c.readLine("Please enter your password: ");
  }
}

public class UiServiceImpl implements UiService {
  @Inject LoginRequestor login;
  boolean loggedIn;

  public void navigateToHomePage() {
    checkLoggedIn();
  }
  private void checkLoggedIn() {
    if (loggedIn) {
      return;
    }
    login.requestCredentials();
    String username = login.getUsername();
    String password = login.getPassword();
    // Do login
    loggedIn = ...;
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    相关资源
    最近更新 更多