首页 > 解决方案 > CDI 中的参数化 bean

问题描述

我正在尝试使用参数创建一个 CDI bean。我的问题是我希望注入类传递这些参数。我怎样才能做到这一点?

例如

class MyBean() {

}

@Dependent
class MyInjectingClass() {
   @Inject MyBean myBean; // and somehow add two int parameters here that MyBean will use in its methods
}

标签: jakarta-eecdi

解决方案


如果ints 只与 的产生完全相关MyBean,那么您可以编写一个生产者方法MyBean来创建它喜欢的实例。例如:

@ApplicationScoped // the "host" of a producer method must itself be a bean
class WhereverYouWantTheProducerMethodToLive {

  @Produces
  @Dependent // make MyBean instances in @Dependent scope
  private MyBean makeMyBean() {
    return new MyBean(1, 2);
  }

}

推荐阅读