我有一个具有可注入(inject)字段的抽象类
public abstract class AbstractPopulator implements ITemplatePopulator {
@Inject
private ITemplatePopulator next;
我有多个继承AbstractPopulator
的类。从某种意义上来说它们很简单
public class ImportsPopulator extends AbstractPopulator
public class FieldsPopulator extends AbstractPopulator
public class LeftHandSidePopulator extends AbstractPopulator
但我需要每个人都有自己的注入(inject) next
字段。例如,对于 leftHandSide
我想要 righthandside
等等。
如何使用 google guice
实现这一目标?
作为解决方案,我决定这样做。在 AbstractPopulator
中,我添加了抽象方法 injectNext
protected abstract void injectNext(ITemplatePopulator next);
并删除了字段next
本身的@Inject
注释。
在每个子类中我都实现了这样的方法
@Override
@Inject
protected void injectNext(@Named("rightHandSidePopulator") ITemplatePopulator next) {
setNext(next);
}
我通过@Named
指定了责任链中下一个填充器的名称。
最后一个填充器很特别
@Override
@Inject(optional = true)
protected void injectNext(@Named("null") ITemplatePopulator next) {
setNext(next);
}
我将Inject
注释的可选
参数设置为true,因为根据Guice
文档
Method and field injections may be optional, which causes Guice to silently ignore them when the dependencies aren't available
因此,如果没有找到名称为 null
的对象,则不会连接 next
。
在模块类中,我绑定(bind)了类
@Override
protected void configure() {
bind(ITemplatePopulator.class)
.annotatedWith(Names.named("packageNamePopulator")).to(PackageNamePopulator.class);
...
并且guice
在需要的地方这样使用它
Injector injector = Guice.createInjector(new PopulatorModule());
ITemplatePopulator first = injector.getInstance(PackageNamePopulator.class); // first in chain
它似乎工作正常,但我不确定这是否是最好的解决方案,并且注释导入是
import com.google.inject.Inject;
import com.google.inject.name.Named;
我是一名优秀的程序员,十分优秀!