gpt4 book ai didi

dependency-injection - CDI,多态性: Is it possible to inject an implementation of bean B into a bean A based on a field initialized during @PostConstruct of A?

转载 作者:行者123 更新时间:2023-12-04 01:44:43 27 4
gpt4 key购买 nike

在我的 JSF 应用程序中,我使用 @ViewScoped bean Publication 来显示/编辑来 self 的数据库的数据。在该 bean 中,有一个用于特定于子类型的数据对象的字段,即根据出版物是书籍还是文章来包含不同的对象。

@ViewScoped
@Named
public class Publication implements Serializable {

@Inject
DatabaseStorage storage;

...

String id;
String type;

PublicationType typedStuff;

@PostConstruct
public void init() {
// Get an URL parameter from the request,
// look up row in database accordingly, initialize String "type".
switch (type) {
case "ARTICLE":
typedStuff = new Article(id);
break;
case "BOOK":
typedStuff = new Book(id);
break;
default:
break;
}
}
}

...具有实现/扩展 PublicationType 的类 ArticleBook

到目前为止,一切都很好,但是我希望 typedStuff 成为一个 CDI bean,这样我就可以在那里注入(inject)有用的资源。

我已阅读 thisthis关于生产者方法的页面,以及 this tutorialthis very related SO question ,但它们都没有准确回答我的问题:我可以根据注入(inject) bean 本身仅在运行时知道的字段进行注入(inject)吗?

我已经让生产者方法像这样工作,但我无法参数化它,所以我无法让该switch工作。

  • 如果我将生成器方法放在单独的类(或 bean)中,那么我将无权访问 type 字段。

  • 如果我将注入(inject)bean注入(inject)到生产者类中,或者将生产者方法移到注入(inject)类中,我会得到循环注入(inject)。

  • 如果我将生产者方法静态地放入注入(inject)类中,我也无权访问,因为 type 不能是静态的。 (不过,因为它只是暂时使用......?)

  • 此外(这可能就是答案),生产者方法在我的注入(inject) bean 的 init 方法之前执行,因此 type 甚至尚未设置。

有人有更好的主意吗?

最佳答案

不,您不能,但您可以根据字段值选择一个 bean。说:

public interface PublicationType {}

@PType("ARTICLE")
public class Article implements PublicationType{}

@PType("BOOK")
public class Book implements PublicationType {}

并定义限定符:

public @interface PType {
String value();
}

并定义一个AnnotationLiteral:

public class PTypeLiteral extends AnnotationLiteral<PType> implements PType {}

然后你可以使用:

public class Publication {

@Any
@Inject
private Instance<PublicationType> publicationTypes;

public void doSomething() {
PType ptype = new PTypeLiteral(type);
// Of course you will have to handle all the kind of exceptions here.
PublicationType publicationType = publicationTypes.select(ptype).get();
}
}

关于dependency-injection - CDI,多态性: Is it possible to inject an implementation of bean B into a bean A based on a field initialized during @PostConstruct of A?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44759896/

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