如何使用Guice的喷油器? [英] How to use Guice's Injector?

查看:63
本文介绍了如何使用Guice的喷油器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Guice,但我不清楚如何使用Injector实例.最好在应用程序引导程序上创建一次Injector实例,并将其设为公共单例?

I'm in process of learning Guice and I don't clearly understand how to use Injector instance. It's better to create Injector instance once on application bootstrap, and make it public singleton?

难道我们总是必须使用Injector#getInstance(SomeClass.class)来获取将Guice的@Inject注释放入其中的类吗?

And is it true that we always must use Injector#getInstance(SomeClass.class) to get classes where we putted Guice's @Inject annotations?

推荐答案

您不应将注入器作为全局单例传递.您是否看过: https://github.com/google/guice/wiki/GettingStarted?请注意,RealBillingService不会使用注入器来获取CreditCardProcessorTransactionLog的实例.相反,Guice在创建实例时会为您处理所有这一切.

You should not pass the injector around as a global singleton. Have you looked at: https://github.com/google/guice/wiki/GettingStarted? Note that RealBillingService does not use the injector to get instances of CreditCardProcessor and TransactionLog. Instead Guice handles all this for you when creating the instance.

如果您需要Guice创建许多相同类型的对象,请考虑使用

If you're in a situation where you need Guice to create many objects of the same type consider using a Provider and injecting that provider.

这篇关于如何使用Guice的喷油器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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