简体   繁体   English

如何使用Google Guice创建需要参数的对象?

[英]How to use Google Guice to create objects that require parameters?

Maybe I am just blind, but I do not see how to use Guice (just starting with it) to replace the new call in this method: 也许我只是盲目,但我不知道如何使用Guice(刚开始)来替换此方法中的new调用:

public boolean myMethod(String anInputValue) {
    Processor proc = new ProcessorImpl(anInputValue);
    return proc.isEnabled();
}

For testing there might be a different implementation of the Processor, so I'd like to avoid the new call and in the course of that get rid of the dependency on the implementation. 对于测试,可能有一个不同的处理器实现,所以我想避免new调用,并在此过程中摆脱对实现的依赖。

If my class could just remember an instance of Processor I could inject it via the constructor, but as the Processors are designed to be immutable I need a new one every time. 如果我的类只记得处理器的一个实例,我可以通过构造函数注入它,但由于处理器被设计为不可变的,我每次都需要一个新的。

How would I go about and achieve that with Guice (2.0) ? 我将如何使用Guice(2.0)实现这一目标?

There is some time since I used Guice now, but I remember something called "assisted injection". 自从我现在使用Guice以来已经有一段时间了,但我记得有一种叫做“辅助注射”的东西。 It allows you to define a factory method where some parameters are supplied and some are injected. 它允许您定义一个工厂方法,其中提供了一些参数并注入了一些参数。 Instead of injecting the Processor you inject a processor factory, that has a factory method that takes the anInputValue parameter. 您可以注入处理器工厂,而不是注入处理器工厂,该工厂具有采用anInputValue参数的工厂方法。

I point you to the javadoc of the FactoryProvider . 我指向FactoryProviderjavadoc I believe it should be usable for you. 我相信它应该对你有用。

You can get the effect you want by injecting a "Provider", which can by asked at runtime to give you a Processor. 您可以通过注入“提供程序”来获得所需的效果,可以在运行时询问为您提供处理器。 Providers provide a way to defer the construction of an object until requested. 提供者提供了一种在请求之前推迟构造对象的方法。

They're covered in the Guice Docs here and here . 他们在这里这里的Guice Docs中都有涉及。

The provider will look something like 提供商看起来像

public class ProcessorProvider implements Provider<Processor> {
    public Processor get() {
        // construct and return a Processor
    }
}

Since Providers are constructed and injected by Guice, they can themselves have bits injected. 由于提供者是由Guice构建和注入的,因此他们自己可以注入比特。

Your code will look something like 你的代码看起来像

@Inject
public MyClass(ProcessorProvider processorProvider) {
    this.processorProvider = processorProvider;
}

public boolean myMethod(String anInputValue) {
    return processorProvider.get().isEnabled(anInputValue);
}

Does your Processor need access to anInputValue for its entire lifecycle? 您的处理器是否需要在整个生命周期内访问anInputValue If not, could the value be passed in for the method call you're using, something like: 如果没有,可以将值传入您正在使用的方法调用,例如:

@Inject
public MyClass(Processor processor) {
    this.processor = processor;
}

public boolean myMethod(String anInputValue) {
    return processor.isEnabled(anInputValue);
}

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

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