【问题标题】:How to discard throwaway @Injected beans?如何丢弃一次性的@Injected bean?
【发布时间】:2019-06-17 11:59:10
【问题描述】:

我的ExampleBean 仅在创建时需要来自UsefulBean1 的信息。所以我可以在得到我想要的信息后丢弃UsefulBean1实例。

@ManagedBean
public class ExampleBean {

   private int value;

   @Inject
   public void setUseful(UsefulBean usefulBean){
        this.value = usefulBean.getValue();
        //bye, bye usefulBean. see ya.
   }
}

但是我的ExampleBean2 呢,它需要在创建时结合来自UsefulBean1UsefulBean2 的信息?

我知道我可以得到他们@Injected 并结合@PostConstruct 方法上的信息:

@ManagedBean
public class ExampleBean2 {

   private int value;

   @Inject 
   private UsefulBean1 usefulBean1;

   @Inject 
   private UsefulBean2 usefulBean2;

   @PostConstruct
   public void init(){
        this.value = this.usefulBean1.getValue() + this.usefulBean2.getValue();
        //from this point on, the usefulBeans fields are useless...
        this.usefulBean1 = null;
        this.usefulBean2 = null;

   }
}

但我保留这两个不再需要的字段(this.usefulBean1this.usefulBean2)让我有点恼火。

我尝试了多参数设置的方法,但无济于事。

这肯定不会破坏任何东西或浪费资源。但是,恕我直言,如果没有字段作为临时一次性变量,代码会更加清晰。

是否可以使用来自多个其他 bean 的数据初始化 CDI bean,而无需将它们设置为字段?

【问题讨论】:

  • 使用构造函数注入。始终使用构造函数注入。 setter 和 field injection 都是另一个更糟糕的时间的后遗症。不要使用它们。甚至不要考虑使用它们。构造函数注入不仅为您提供可测试的、不可变的对象;它也完全解决了你的问题。
  • @BoristheSpider 构造函数注入将阻止 bean 被代理,因为关于无参数非私有构造函数的规范:docs.jboss.org/cdi/spec/1.2/cdi-spec.html#unproxyable
  • 那就不要使用那个糟糕的 CDI 框架。 DI 框架应该帮助您编写好的代码,而不是强迫您编写无法测试、无法维护的废话——这与控制反转模式的意图完全相反。
  • 规范中有。不能怪框架。

标签: java dependency-injection cdi idioms


【解决方案1】:

(首先@ManagedBean与CDI无关,不应该使用。)

(第二,总是考虑寿命(“范围”):每个 bean 应该活多久?对于这个例子,我假设你希望 ExampleBean2 是你的应用程序中唯一的这样的 bean,所以我会用@ApplicationScoped 标记它(你上面的一些cmets 参考代理所以这是一个合理的猜测)。你可以用@RequestScoped@Dependent 或其他一些范围来注释它。如果你不注释它带有任何范围注释,那么它的行为就像你用@Dependent注释它一样。)

像这样:

@ApplicationScoped
public class ExampleBean2 {

  private final int value;

  /**
   * @deprecated To be used only by the CDI framework, not end users.
   */
  @Deprecated
  protected ExampleBean2() {
    super();
  }

  @Inject
  public ExampleBean2(final UsefulBean1 usefulBean1, final UsefulBean2 usefulBean2) {
    super();
    this.value = this.usefulBean1.getValue() + this.usefulBean2.getValue();
  }

}

【讨论】:

    猜你喜欢
    • 2011-01-05
    • 1970-01-01
    • 1970-01-01
    • 2013-04-30
    • 2015-05-23
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    相关资源
    最近更新 更多