gpt4 book ai didi

java - 指定子类的注入(inject)

转载 作者:太空宇宙 更新时间:2023-11-04 10:35:01 25 4
gpt4 key购买 nike

我有一个具有可注入(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;

关于java - 指定子类的注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49587691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com