简体   繁体   English

如何编写未明确创建对象的Guice Provider?

[英]How do I write a Guice Provider that doesn't explicitly create objects?

Say I have a ClassWithManyDependencies. 假设我有一个ClassWithManyDependencies。 I want to write a Guice Provider for this class, in order to create a fresh instance of the class several times in my program (another class will depend on this Provider and use it at several points to create new instances). 我想为这个类编写一个Guice Provider,以便在我的程序中多次创建一个类的新实例(另一个类将依赖于这个Provider并在几个点使用它来创建新实例)。

One way to achieve this is by having the Provider depend on all the dependencies of ClassWithManyDependencies. 实现此目的的一种方法是让Provider依赖于ClassWithManyDependencies的所有依赖项。 This is quite ugly. 这很难看。

Is there a better way to achieve this? 有没有更好的方法来实现这一目标?

Note - I certainly don't want the Provider to depend on the injector. 注意 - 我当然不希望Provider依赖注入器。 Another option I considered is having ClassWithManyDependencies and ClassWithManyDependenciesProvider extend the same base class, but it's butt ugly. 我考虑的另一个选择是让ClassWithManyDependencies和ClassWithManyDependenciesProvider扩展相同的基类,但它很难看。

As mentioned on the mailing list, anywhere you can inject ClassWithManyDependencies you can simply inject Provider<ClassWithManyDependencies> instead, no need to write anything special yourself. 正如邮件列表中所提到的,无论你在哪里注入ClassWithManyDependencies都可以简单地注入Provider<ClassWithManyDependencies> ,而不需要自己编写任何特殊内容。 Guice does this for you. Guice为你做这件事。

You shouldn't have to write a provider except to integrate with other frameworks. 除了与其他框架集成之外,您不必编写提供程序。

Just DON'T bind your ClassWithManyDependencies in scope SINGLETON and in the class that wants to build many instances, instead of having a ClassWithManyDependencies instance injected you have a Provider injected. 只是不要在范围SINGLETON和想要构建许多实例的类中绑定ClassWithManyDependencies,而不是注入ClassWithManyDependencies实例,而是注入了Provider。 (Guice can do that for free for every binded class) (Guice可以为每个绑定类免费提供)

On this provider you can just call get(), if not in scope SINGLETON it makes a fresh new instance each time. 在这个提供者上你可以调用get(),如果不在范围SINGLETON中,它每次都会创建一个全新的实例。

Now if you are in the tricky case that ClassWithManyDependencies relies both on some GUICE IOC and on some constructor parameters, then you shall go for Assisted Injections 现在,如果您遇到一些棘手的情况,ClassWithManyDependencies依赖于某些GUICE IOC和一些构造函数参数,那么您应该选择Assisted Injections

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM