gpt4 book ai didi

java - Guice -如何在扩展抽象模块的类中注入(inject)依赖项 - Java

转载 作者:行者123 更新时间:2023-12-02 03:45:29 26 4
gpt4 key购买 nike

我必须从EnvironmentModule触发TestDriver.startPoller(),因为EnvironmentModule是从Abstractmodule扩展而来的不确定如何在 EnvironmentModule 中注入(inject)依赖项是否可能?如果不是,我如何从 EnvironmentModule

触发 TestDriver.startPoller()
@Log4j2
@AllArgsConstructor(onConstructor = @__(@Inject))
public class TestDriver {

private ClientTrafficCalculator clientTrafficCalculator;
private TaskAllocator taskAllocator;


@SneakyThrows
public void startPoller() {


new Thread(clientTrafficCalculator::prepareRateLimiterForAllClients).start();
new Thread(taskAllocator::processPendingRecordsInDDB).start();
log.info("All threads are started");

}

}

环境模块

    @Log4j2
@AllArgsConstructor(onConstructor = @__(@Inject))
public class EnvironmentModule extends AbstractModule {

private TestDriver testDriver;


@SneakyThrows
public EnvironmentModule(final String[] args) {

marketplace = System.getProperty("realm", "USTest");
final String realm = getPropOrDefault("realm", "USTest");
final String root = getPropOrDefault("root", ".");
AppConfig.initialize(SERVICE_NAME, null, appConfigArgs);

TestDriver.startPoller();

}

@Override
public void configure() {
install(new TomcatContainerModule(new ServiceModule(Test)));
}
}

预期:

TestDriver.startPoller();//这工作正常

当前结果

TestDriver.startPoller();//抛出空指针异常,因为它没有被注入(inject)并且 TestDriver 为 null

最佳答案

我想我找到了答案,我们可以做如下的事情

@Log4j2
public class TestDriver extends AbstractModule {


@Override
public void configure() {
requestInjection(this);
}

@Inject
public void startPoller(ClientTrafficCalculator clientTrafficCalculator,
TaskAllocator taskAllocator, PManager pManager) {

new Thread(pManager::name).start();

}


}

我们必须安装它,安装将触发该方法

install(new TestDriver()); //trigger pollers for proxy and task allocation

谢谢Jk

关于java - Guice -如何在扩展抽象模块的类中注入(inject)依赖项 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56810648/

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