How to make a CDI bean lazily initialized?

前端 未结 3 1068
慢半拍i
慢半拍i 2021-01-05 17:23

I am using Weld implementation of CDI 1.0 and I cannot find way how to make bean lazy like in Spring (using @Lazy or lazy-init in XML). Is there a

相关标签:
3条回答
  • 2021-01-05 17:56

    See my answer on: http://www.adam-bien.com/roller/abien/entry/lazy_injection_with_javax_inject

    Using

     @Inject
    Instance<MyObject> object;
    

    the bean is initialized only when needed ... isn't that what you want?

    0 讨论(0)
  • 2021-01-05 18:05

    No, this isn't possible in CDI. The closest thing you could get would be to create a new InjectionPoint (using an Extension) implementation that gives a proxy and the proxy would initialize everything on the first method invocation.

    0 讨论(0)
  • 2021-01-05 18:13

    If the bean you're injecting is in a normal scope (@SessionScoped, @RequestScoped etc), it will be lazily instantiated. What you get in your client bean is a proxy that doesn't point to a concrete instance until the first time you invoke a method on the proxy.

    As others have already pointed out, @Inject Instance<MyBean> myBeanInstance; can also be used to establish an explicit lazy instantiation.

    0 讨论(0)
提交回复
热议问题