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
}

解决方法

如果intMyBean的产生完全相关,那么您可以编写一个producer method来制作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);
  }

}