【问题标题】:Parameterized bean in CDICDI 中的参数化 bean
【发布时间】:2021-02-12 17:20:43
【问题描述】:

我正在尝试创建一个带有参数的 CDI bean。我的问题是我希望注入类传递这些参数。我该怎么做?

例如

class MyBean() {

}

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

【问题讨论】:

  • 如果适用,可以提供带有@Produces的procuder方法。
  • 你能给我写一个非常简单的例子吗?我真的不明白它对我有什么帮助。
  • 我认为注入是在第一次使用 myBean 时完成的。您可以尝试在 MyInjectingClass 的 @PostConstruct-Method 中设置参数。

标签: jakarta-ee cdi


【解决方案1】:

如果ints 与MyBean 的产生完全相关,那么您可以编写一个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);
  }

}

【讨论】:

    猜你喜欢
    • 2012-07-23
    • 2023-03-10
    • 1970-01-01
    • 2012-12-29
    • 1970-01-01
    • 2015-04-20
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    相关资源
    最近更新 更多