将参数传递给Guice @Provides方法 [英] Passing parameters to Guice @Provides method

查看:59
本文介绍了将参数传递给Guice @Provides方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Guice模块,该模块具有一个@Provides方法,该方法带有2个参数并返回接口的实现:

I have a Guice module that has a @Provides method that takes 2 parameters and returns the implementation of the interface:

public class **ClientModule** extends **AbstractModule**{

@Override
protected void configure(){

}

@Singleton
@Provides
protected ClientInterfaces provideService(String param1, String param2){
   returns something
 }

}

在注入模块的主类中,如何将参数传递给@Provides方法?

In my main class that injects the module, how do I pass the params to the @Provides method?

public MainClass{
main(){
Injector injector = Guice.createInjector( new ClientModule());
MainClass mainClass = injector.getInstance(MainClass.class);

}

这将引发Null指针异常param1

This throws a Null pointer exception param1

推荐答案

您不会自己调用Provides方法,当您首次需要访问(在这种情况下)ClientInterfaces实现时,Guice会调用该方法.

You don't call a provides method yourself, it is called by Guice when you first need to access (in this case) your ClientInterfaces Implementation.

我认为,您需要配置参数来初始化ClientInterfaces.

I assume, you need configuration parameters to initialize your ClientInterfaces.

所以尝试Binding-Annotation,最简单的是@Named:

So try Binding-Annotation, the simplest is @Named:

configure() {
   bindConstant().annotatedWith(Names.named("hostName")).to("myHost");
   bindConstant().annotatedWith(Names.named("port")).to("8080");
}
@Provides
@Singleton
public MyService provideMyService(@Named("hostName") String host, @Named("port") String port) {
   // init MyService 
   return ....
}

当然,通常您将从属性文件System.props中读取myHost和"8080"而不是硬编码常量.

Of course, you normally will read myHost and "8080" from a properties file System.props instead of hard coding constants.

第一次需要注入MyService时,Guice会注意到它需要注释字符串才能满足Provide方法的要求,并搜索绑定到Annotatioon名称的值...

The first time you need to Inject a MyService, Guice will notice that it needs to annotated Strings to fulfill the requirements of the provide method and search for the values bound to the Annotatioon name ...

这篇关于将参数传递给Guice @Provides方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆