gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:41:15 25 4
gpt4 key购买 nike

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

最佳答案

您的数据就是:数据。不要注入(inject)数据,除非它在您获取模块之前已定义并且对于应用程序的其余部分是不变的。

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

如果您希望在注入(inject)开始后检索您的数据,则根本不应尝试注入(inject)它。然后你应该做的是在你需要的任何地方注入(inject)你的 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 = ...;
}
}

关于java - 使用 Guice 注入(inject)运行时生成的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33254075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com