2015-10-21 60 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 = ...; 
    } 
}