@EntryPoint public class App { ... @Produces @Supported private MyBaseWidget createWidget() { return (Canvas.isSupported()) ? new MyHtml5Widget() : new MyDefaultWidget(); } }
Producer methods and fields act as sources of objects to be injected. They are useful when additional control over object creation is needed before injections can take place e.g. when you need to make a decision at runtime before an object can be created and injected.
@EntryPoint public class App { ... @Produces @Supported private MyBaseWidget createWidget() { return (Canvas.isSupported()) ? new MyHtml5Widget() : new MyDefaultWidget(); } }
@ApplicationScoped public class MyComposite extends Composite { @Inject @Supported private MyBaseWidget widget; ... }
Producers can also be scoped themselves. By default, producer methods are dependent-scoped, meaning they get called every time an injection for their provided type is requested. If a producer method is scoped @Singleton for instance, the method will only be called once, and the bean manager will inject the instance from the first invokation of the producer into every matching injection point.
public class App { ... @Produces @Singleton private MyBean produceMyBean() { return new MyBean(); } }
For more information on CDI producers, see the CDI specification and the WELD reference documentation.