JBoss Community Archive (Read Only)

Errai

Producers

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.

App.java
@EntryPoint
public class App {
  ...

  @Produces @Supported
  private MyBaseWidget createWidget() {
    return (Canvas.isSupported()) ? new MyHtml5Widget() : new MyDefaultWidget();
  }
}
MyComposite.java
@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.

Singleton producer
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.

JBoss.org Content Archive (Read Only), exported from JBoss Community Documentation Editor at 2020-03-10 12:34:51 UTC, last content change 2012-06-20 15:32:20 UTC.