6

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 way how to tell CDI's Injector not to initialize bean on startup?

palacsint
  • 28,416
  • 10
  • 82
  • 109
Xorty
  • 18,367
  • 27
  • 104
  • 155

3 Answers3

8

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?

Jan Galinski
  • 11,768
  • 8
  • 54
  • 77
  • [According to Adam Bien](http://www.adam-bien.com/roller/abien/entry), there's an alternative to this that _might_ be a little more lightweight: merely injecting a `Provider>` instead of an `Instance>`, all the rest being the same. – Hein Blöd Apr 28 '16 at 15:29
  • 1
    @Hein Blöd The link to the entry in Adam Bien's weblog has changed to [Lazy Injection with javax.inject.Provider](http://www.adam-bien.com/roller/abien/entry/lazy_injection_with_javax_inject). – ltlBeBoy Jun 14 '17 at 10:34
7

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.

LightGuard
  • 5,298
  • 19
  • 19
  • So, by using @Inject Instance beantypeProvider; this should work right ? – David Hofmann Jul 24 '14 at 07:13
  • 1
    Um, my first reaction is to say that might work. Though if you're using a CDI 1.0 implementation Instance does leak memory of dependant scoped instances. – LightGuard Sep 16 '14 at 21:04
  • Which implementation are you talking about ? where is your reference ? – David Hofmann Sep 17 '14 at 12:58
  • 1
    Both OWB and Weld had the problem. See http://stackoverflow.com/questions/8385190/cdi-application-and-dependent-scopes-can-conspire-to-impact-garbage-collection for more information. It was a both a spec and an implementation issue. – LightGuard Sep 17 '14 at 17:19
  • So, as long as I can use the Instance.destroy(instance) I am ok :) Thanks – David Hofmann Sep 18 '14 at 01:08
5

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.

jvalli
  • 721
  • 4
  • 7