ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-11-19 15:00:53  阅读:141  来源: 互联网

标签:dependency-injection guice java


我有一个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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有