How to make a CDI bean lazily initialized?

我只是一个虾纸丫 提交于 2019-12-01 03:34:12

问题


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?


回答1:


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.




回答2:


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?




回答3:


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.



来源:https://stackoverflow.com/questions/12630508/how-to-make-a-cdi-bean-lazily-initialized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!