【发布时间】: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