编程语言
首页 > 编程语言> > java-使用Guice注入运行时生成的值

java-使用Guice注入运行时生成的值

作者:互联网

我有一个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的实例.
我该如何实现?

解决方法:

您的数据就是这样:数据.除非在获取模块之前就已定义数据,否则不要注入数据,对于其他应用程序来说,数据是恒定的.

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 = ...;
  }
}

标签:dependency-injection,guice,java
来源: https://codeday.me/bug/20191119/2037039.html