第三章 【第四节】 @Provides方法(@Provides Methods):Guice指导教程(原创翻译)

目录
[隐藏]

ProvidesMethods

@Provides方法 @Provides Methods

当你需要创建一个对象时,可以使用@Provides方法。这个方法在modele里定义,并且必须有一个带@Provides注解。这个方法的返回类型将是绑定的类型。每当注入需要的这个类型的实例时,将会调用这个方法。
When you need code to create an object, use an @Provides method. The method must be defined within a module, and it must have an @Provides annotation. The method’s return type is the bound type. Whenever the injector needs an instance of that type, it will invoke the method.

如果@Provides方法里有一个类似@PayPal或者@Named(“Checkout”)的绑定注解,Guice将会绑定这个被标注的类型。依赖关系可以作为参数传递给方法。注入器会在调用这个方法前一次执行这些绑定。
If the @Provides method has a binding annotation like @PayPal or @Named(“Checkout”), Guice binds the annotated type. Dependencies can be passed in as parameters to the method. The injector will exercise the bindings for each of these before invoking the method.

抛异常 Throwing Exceptions

Guice不允许Providers抛异常。从@Provides方法中抛出的异常将会被包含在ProvisionException异常中。允许从@Provides方法中抛出任意类型的异常不是最好的做法——执行期,或者检查期。如果你有些情况下需要抛出异常,你可以用ThrowingProviders extension @CheckedProvides方法
Guice does not allow exceptions to be thrown from Providers. Exceptions thrown by @Provides methods will be wrapped in a ProvisionException. It is bad practice to allow any kind of exception to be thrown — runtime or checked — from an @Provides method. If you need to throw an exception for some reason, you may want to use the ThrowingProviders extension @CheckedProvides methods.


实例

@Provides Methods(@Provides注解方法):用@Provides来注解方法产生需要的对象。

执行结果:
run @Provides
jdbcUrl==>jdbc:mysql://localhost/pizza loginTimeout==>20 seconds

可以看到,在module里没有绑定int类型的值,却在依赖时注入了。

下一节:Provider Bindings


说明:

      鉴于网上guice中文资料较少,出于个人爱好,对该项目下的用户API文档进行翻译。如有翻译不恰当之处,还望指正。

      google Guice 项目地址:https://github.com/google/guice

      Guice 英文API地址:https://github.com/google/guice/wiki/LinkedBindings

分享到:

发表评论

昵称

沙发空缺中,还不快抢~