gpt4 book ai didi

guice - 如何将注入(inject)参数和辅助参数传递给 Guice Provider?

转载 作者:行者123 更新时间:2023-12-01 11:46:07 27 4
gpt4 key购买 nike

我有以下供应商:

  public class GuiceResourceProvider implements Provider<WebResource> {

@Inject
private Configuration configuration;
@Inject
private Environment environment;

private String name;

@Inject
public GuiceResourceProvider(@Assisted("name") String name) {
this.name = name;
}

@Override
public WebResource get() {
if (name == "default") {
String connectionsDSResourceUrl = "http://localhost:" + this.configuration.getHttpConfiguration().getPort();
Client connectionsDSHttpClient = new JerseyClientBuilder().using(this.configuration.getHttpClientConfiguration()).using(this.environment).build();
connectionsDSHttpClient.addFilter(new RequestIdClientFilter());
return connectionsDSHttpClient.resource(connectionsDSResourceUrl);
} else if(name == "other"){
return ......
}
}
}

我需要创建此 Provider 的 2 个实例,一个将绑定(bind)一个带有“default”注释的 WebResource 注入(inject),一个将绑定(bind)一个带有“other”注释的 WebResource 注入(inject)。

让 Guice 创建 Provider 实例如下:

    bind(WebResource.class).annotatedWith(Names.named("default")).toProvider(GuiceResourceProvider.class).in(Scopes.SINGLETON);
bind(WebResource.class).annotatedWith(Names.named("other")).toProvider(GuiceResourceProvider.class).in(Scopes.SINGLETON);

注入(inject)参数没问题,但我无法提供自定义参数。如果我尝试手动实例化一个实例并提供自定义参数,那么注入(inject)的当然有问题。如果我遵循辅助符号,问题是我需要在模块中注入(inject)提供者的工厂,当然,这是完全关闭的!

有人能帮忙吗?

最佳答案

对于可能感兴趣的每个人,我找到了答案。如果您想将注入(inject)参数和自定义参数都传递给提供者,请将注入(inject)参数从构造函数移至字段,并使用构造函数传递您自己的参数。绑定(bind)时,首先创建 Provider 的一个实例,将参数传递给构造函数,然后在该实例上调用 requestInjection 以将其添加到注入(inject)图中,然后将您的类绑定(bind)到 Provider 实例,如下所示:

GuiceResourceProvider guiceResourceProvider = new GuiceResourceProvider("default");
requestInjection(guiceResourceProvider);

绑定(bind)(WebResource.class).annotatedWith(Names.named("default")).toProvider(guiceResourceProvider).in(Scopes.SINGLETON);

这是提供者:

public class GuiceResourceProvider implements Provider<WebResource> {

@Inject
private Configuration configuration;
@Inject
private Environment environment;

private String name;

@Inject
public GuiceResourceProvider(String name) {
this.name = name;
}

@Override
public WebResource get() {
if (name == "default") {
String connectionsDSResourceUrl = "http://localhost:" + this.configuration.getHttpConfiguration().getPort();
Client connectionsDSHttpClient = new JerseyClientBuilder().using(this.configuration.getHttpClientConfiguration()).using(this.environment).build();
connectionsDSHttpClient.addFilter(new RequestIdClientFilter());
return connectionsDSHttpClient.resource(connectionsDSResourceUrl);
} else if(name == "other"){
return ......
}
}

关于guice - 如何将注入(inject)参数和辅助参数传递给 Guice Provider?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15065943/

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