2015-10-21 59 views
3

我有一个Context类,它是一个在运行时逐渐填充的键值对。使用Guice来注入运行时生成的值

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

例如:

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(); 
    } 
} 

我希望能够创建使用吉斯的UseUiServiceTask的实例。 我该如何做到这一点?

+1

您是否尝试过与供应商? –

+0

如果我得到它正确的提供者不适用于我的情况。你能详细说明吗? – Ikaso

+0

我在想像http://stackoverflow.com/a/15493413/4462333 这样的东西如果它不锻炼,我可能会误解你的问题。你能编辑它来添加更多与你的问题有关的代码/信息吗? –

回答

3

你的数据就是这样的:数据。除非在获取模块之前定义数据,否则不要注入数据,对于其他应用程序而言,数据不变。

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