0

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?

jactor
  • 1

1 Answers1

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).

LightGuard
  • 5,298
  • 19
  • 19
  • Dear LightGuard, thanks for your reply. I will investigate in that direction. To answer your question about creating beans with producers that reqire injection, suppose that a framework for desktop (i.e. swing) application wants to expose methods for creating views. The best way to let clients create those views is to provide factory interfaces. Now my framework can use those factories for creating views, but those views can't use DI. So my idea was to let a producer expose that views to CDI, letting it to manage dependecy injection. I think that this behavior could be useful... – jactor Jan 24 '13 at 23:29
  • That's the kind of situation the BeanProvider was created. – LightGuard Jan 25 '13 at 00:04
  • To inject CDI beans into an instance created with 'new' use BeanProvider#injectFields – Dar Whi Feb 15 '13 at 22:58