enable CDI injection into a bean created by a producer method

混江龙づ霸主 提交于 2021-02-11 17:52:23

问题


Producer methods are very useful for creating instances programmatically and publishing them in a context. The problem is that all properties of an instance created by new and returned by a producer method are not injected by CDI. In the Weld documentation I've read that this is an intentional behaviour, but in many cases injection in those beans would be very useful.

Is there a workaround to enable injection into such beans?


回答1:


First, I have to ask why you are using Producers for beans that require injection anyway.

That aside, you need to create a new instance from the BeanManager. Take a look at https://github.com/apache/incubator-deltaspike/blob/master/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/provider/BeanProvider.java#L115 for some ideas (you could simply inject the BeanManager as a parameter to the Producer method and do the same code).



来源:https://stackoverflow.com/questions/14485661/enable-cdi-injection-into-a-bean-created-by-a-producer-method

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