使用Google Guice和静态方法注入Util类? [英] Inject Util Class with Google Guice vs static Methods?
本文介绍了使用Google Guice和静态方法注入Util类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道用google guice注入实用程序方法是否是一种好方法。
I'm wondering if it is a good style to inject utility methods with google guice.
假设我们有一个转换器实用程序类:
Let's say we have a Converter Utility Class:
public class UtilClass
{
public static Result convert(Source src)
{
//Do conversion
return result;
}
}
我的想法是使用guice将此实用程序注入像这样的单身人士
My idea is to use guice to inject this Utility as Singleton like this
@Singleton
public class UtilClass
{
public Result convert(Source src)
{
//Do conversion
return result;
}
}
建议使用guice构建的应用程序采用哪种方式?
Which way is recommended for an Application built with guice?
推荐答案
这取决于 convert()
方法的性质。
It depends on the nature of your convert()
method.
如果是的话
- 简单
- 确定性(即不依赖于其他参数)
- 没有副作用
- 不太可能改变
- etc
- simple
- deterministic (i.e. doesn't depend on additional parameters)
- have no side effects
- is unlikely to change
- etc
您可以将其保留为静态实用程序方法。
you can keep it as a static utility method.
否则它是一个很好的依赖注入候选者(你可以将它重命名为 ConversionService
以使其更清晰)。
Otherwise it's a good candidate for dependecy injection (you can rename it to ConversionService
to make it more clear).
这篇关于使用Google Guice和静态方法注入Util类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文