问题
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