<?xml version="1.0" encoding="UTF-8"?>
<chapter id="sid-5931402">
   <title>Dependency Injection</title>
   <para>
      The core Errai IOC module implements the
      <emphasis role="italics">
        <ulink url="http://download.oracle.com/otndocs/jcp/dependency_injection-1.0-final-oth-JSpec/">JSR-330 Dependency Injection</ulink>
      </emphasis>
      specification for in-client component wiring.
    </para>
   <para>Dependency injection (DI) allows for cleaner and more modular code, by permitting the implementation of decoupled and type-safe components. By using DI, components do not need to be aware of the implementation of provided services. Instead, they merely declare a contract with the container, which in turn provides instances of the services that component depends on.</para>
   <note>
      <title>Classpath Scanning and ErraiApp.properties</title>
      <para>
        Errai only scans the contents of classpath locations (JARs and directories) that have
        <link linkend="sid-5931354">
          a file called
          <code>ErraiApp.properties</code>
        </link>
        at their root. If dependency injection is not working for you, double-check that you have an
        <code>ErraiApp.properties</code>
        in every JAR and directory that contains classes Errai should know about.
      </para>
   </note>
   <para>A simple example:</para>
   <informalexample>
      <programlisting language="java">
public class MyLittleClass {
  private final TimeService timeService;

  @Inject
  public MyLittleClass(TimeService timeService) {
    this.timeService = timeService;
  }

  public void printTime() {
    System.out.println(this.timeService.getTime());
  }
}
</programlisting>
   </informalexample>
   <para>
      In this example, we create a simple class which declares a dependency using
      <code>
        <ulink url="http://download.oracle.com/javaee/6/api/javax/inject/Inject.html">@Inject</ulink>
      </code>
      for the interface
      <code>TimeService</code>
      . In this particular case, we use constructor injection to establish the contract between the container and the component. We can similarly use field injection to the same effect:
    </para>
   <informalexample>
      <programlisting language="java">
public class MyLittleClass {
  @Inject
  private TimeService timeService;

  public void printTime() {
    System.out.println(this.timeService.getTime());
  }
}
</programlisting>
   </informalexample>
   <para>
      In order to inject
      <code>TimeService</code>
      , you must annotate it with
      <code>@ApplicationScoped</code>
      or the Errai DI container will not acknowledge the type as a bean.
    </para>
   <informalexample>
      <programlisting language="java">
@ApplicationScoped
public class TimeService {
}
</programlisting>
   </informalexample>
   <para>
      
    </para>
   <tip>
      <title>Best Practices</title>
      <para>Although field injection results in less code, a major disadvantage is that you cannot create immutable classes using the pattern, since the container must first call the default, no argument constructor, and then iterate through its injection tasks, which leaves the potential – albeit remote – that the object could be left in an partially or improperly initialized state. The advantage of constructor injection is that fields can be immutable (final), and invariance rules applied at construction time, leading to earlier failures, and the guarantee of consistent state.</para>
   </tip>
   <section id="sid-5931407">
      <title>Container Wiring</title>
      <para>
        In contrast to
        <ulink url="http://code.google.com/p/google-gin/">Gin</ulink>
        , the Errai IOC container does not provide a programmatic way of creating and configuring injectors. Instead, container-level binding rules are defined by implementing a
        <code>
            <ulink url="http://download.oracle.com/javaee/6/api/javax/inject/Provider.html">Provider</ulink>
        </code>
        , which is scanned for and auto-discovered by the container.
      </para>
      <para>
        A
        <code>Provider</code>
        is essentially a factory which produces type instances within in the container, and defers instantiation responsibility for the provided type to the provider implementation. Top-level providers use the standard
        <code>javax.inject.Provider&lt;T&gt;</code>
        interface.
      </para>
      <para>
        Types made available as
        <emphasis role="italics">top-level</emphasis>
        providers will be available for injection in any managed component within the container.
      </para>
      <para>
        Out of the box, Errai IOC implements these default top-level providers, all defined in the
        <code>org.jboss.errai.ioc.client.api.builtin</code>
        package:
      </para>
      <itemizedlist>
         <listitem>
            <para>
               <code>CallerProvider         :</code>
            Makes RPC
            <code>Caller&lt;T&gt;</code>
            objects available for injection.
          </para>
         </listitem>
         <listitem>
            <para>
               <code>DisposerProvider       :</code>
            Makes Errai IoC
            <code>Disposer&lt;T&gt;</code>
            objects available for injection.
          </para>
         </listitem>
         <listitem>
            <para>
               <code>InitBallotProvider     :</code>
            Makes instances of
            <code>InitBallot</code>
            available for injection.
          </para>
         </listitem>
         <listitem>
            <para>
               <code>IOCBeanManagerProvider :</code>
            Makes Errai's client-side bean manager,
            <code>IOCBeanManager</code>
            , available for injection.
          </para>
         </listitem>
         <listitem>
            <para>
               <code>MessageBusProvider     :</code>
            Makes Errai's client-side
            <code>MessageBus</code>
            singleton available for injection.
          </para>
         </listitem>
         <listitem>
            <para>
               <code>RequestDispatcherProvider :</code>
            Makes an instance of the
            <code>RequestDispatcher</code>
            available for injection.
          </para>
         </listitem>
         <listitem>
            <para>
               <code>RootPanelProvider      :</code>
            Makes GWT's
            <code>RootPanel</code>
            singleton injectable.
          </para>
         </listitem>
         <listitem>
            <para>
               <code>SenderProvider         :</code>
            Makes MessageBus
            <code>Sender&lt;T&gt;</code>
            objects available for injection.
          </para>
         </listitem>
      </itemizedlist>
      <para>
        Implementing a
        <code>Provider</code>
        is relatively straight-forward. Consider the following two classes:
      </para>
      <para>
        <emphasis role="strong">TimeService.java</emphasis>
      </para>
      <informalexample>
         <programlisting language="java">
public interface TimeService {
  public String getTime();
}
</programlisting>
      </informalexample>
      <para>
        <emphasis role="strong">TimeServiceProvider.java</emphasis>
      </para>
      <informalexample>
         <programlisting language="java">
@IOCProvider
@Singleton
public class TimeServiceProvider implements Provider&lt;TimeService&gt; {
  @Override
  public TimeService get() {
    return new TimeService() {
      public String getTime() {
        return "It's midnight somewhere!";
      }
    };
  }
}
</programlisting>
      </informalexample>
      <para>If you are familiar with Guice, this is semantically identical to configuring an injector like so:</para>
      <informalexample>
         <programlisting language="java">
Guice.createInjector(new AbstractModule() {
  public void configure() {
    bind(TimeService.class).toProvider(TimeServiceProvider.class);
  }
 }).getInstance(MyApp.class);
</programlisting>
      </informalexample>
      <para>
        As shown in the above example code, the annotation
        <code>@IOCProvider</code>
        is used to denote top-level providers.
      </para>
      <para>The classpath will be searched for all annotated providers at compile time.</para>
      <important>
         <para>Top-level providers are regular beans, so they can inject dependencies–particularly from other top-level providers–as necessary.</para>
      </important>
   </section>
   <section id="sid-5931332">
      <title>Wiring server side components</title>
      <para>
        By default, Errai uses Google Guice to wire server-side components. When deploying services on the server-side, it is currently possible to obtain references to the
        <code>MessageBus</code>
        ,
        <code>RequestDispatcher</code>
        , the
        <code>ErraiServiceConfigurator</code>
        , and
        <code>ErraiService</code>
        by declaring them as injection dependencies in Service classes, extension components, and session providers.
      </para>
      <para>Alternatively, supports CDI based wiring of server-side components. See the chapter on Errai CDI for more information.</para>
   </section>
   <section id="sid-20938792">
      <title>Scopes</title>
      <para>
        Out of the box, the IOC container supports three bean scopes,
        <code>@Dependent</code>
        ,
        <code>@Singleton</code>
        and
        <code>@EntryPoint</code>
        . The singleton and entry-point scopes are roughly the same semantics.
      </para>
      <section id="sid-24674461">
         <title>Dependent Scope</title>
         <para>
          In Errai IOC, all client types are valid bean types if they are default constructable or can have construction dependencies satisfied. These unqualified beans belong to the dependent pseudo-scope. See:
          <ulink url="http://docs.jboss.org/weld/reference/latest/en-US/html/scopescontexts.html#d0e1997">Dependent Psuedo-Scope from CDI Documentation</ulink>
        </para>
         <para>
          Additionally, beans may be qualified as
          <code>@ApplicationScoped</code>
          ,
          <code>@Singleton</code>
          or
          <code>@EntryPoint</code>
          . Although
          <code>@ApplicationScoped</code>
          and
          <code>@Singleton</code>
          are supported for completeness and conformance, within the client they effectively result in behavior that is identical.
        </para>
         <example>
            <title>Example dependent scoped bean</title>
            <programlisting language="java">
public void MyDependentScopedBean {
  private final Date createdDate;

  public MyDependentScopedBean {
    createdDate = new Date();
  }  
}
</programlisting>
         </example>
         <example>
            <title>Example ApplicationScoped bean</title>
            <programlisting language="java">
@ApplicationScoped
public void MyClientBean {
  @Inject MyDependentScopedBean bean;

  // ... //
}
</programlisting>
         </example>
         <important>
            <title>Availability of dependent beans in the client-side BeanManager</title>
            <para>
            As is mentioned in the
            <link linkend="sid-21627016_Client-SideBeanManager-AvailabilityOfBeans">bean manager documentation</link>
            , only beans that are
            <emphasis role="italics">explicitly</emphasis>
            scoped will be made available to the bean manager for lookup. So while it is not necessary for regular injection, you must annotate your dependent scoped beans with
            <code>@Dependent</code>
            if you wish to dynamically lookup these beans at runtime.
          </para>
         </important>
      </section>
   </section>
   <section id="sid-20938794">
      <title>Built-in Extensions</title>
      <section id="sid-20938797">
         <title>Bus Services</title>
         <para>As Errai IOC provides a container-based approach to client development, support for Errai services are exposed to the container so they may be injected and used throughout your application where appropriate. This section covers those services.</para>
         <section id="sid-20938797_BusServices-@Service">
            <title>@Service</title>
            <para>
            The
            <code>org.jboss.errai.bus.server.annotations.Service</code>
            annotation is used for binding service endpoints to the bus. Within the Errai IOC container you can annotate services and have them published to the bus on the client (or on the server) in a very straight-forward manner:
          </para>
            <example>
               <title>A simple message receiving service</title>
               <programlisting language="java">
@Service
public class MyService implements MessageCallback {
  public void callback(Message message) {
    // ... //
  }
}
</programlisting>
            </example>
            <para>Or like so ...</para>
            <example>
               <title>Mapping a callback from a field of a bean</title>
               <programlisting language="java">
@Singleton
public class MyAppBean {
   @Service("MyService")
   private final MessageCallback myService = new MesageCallback() {
     public void callback(Message message) {
       // ... //
     }
   }
}
</programlisting>
            </example>
            <para>As with server-side use of the annotation, if a service name is not explicitly specified, the underlying class name or field name being annotated will be used as the service name.</para>
         </section>
         <section id="sid-20938797_BusServices-@Local">
            <title>@Local</title>
            <para>
            The
            <code>org.jboss.errai.bus.server.api.Local</code>
            annotation is used in conjunction with the
            <code>@Service</code>
            annotation to advertise a service only for visibility on the local bus and thus, cannot receive messages across the wire for the service.
          </para>
            <example>
               <title>A local only service</title>
               <programlisting language="java">
@Service @Local
public class MyLocalService implements MessageCallback {
  public void callback(Message message) {
    // ... //
  }
}
</programlisting>
            </example>
         </section>
         <section id="sid-20938797_BusServices-LifecycleImpactofServices">
            <title>Lifecycle Impact of Services</title>
            <para>
            Services which are registered with ErraiBus via the bean manager through use of the
            <code>@Service</code>
            annotation, have de-registration hooks tied implicitly to the destruction of the bean. Thus,
            <link linkend="sid-22872238">destruction of the bean</link>
            implies that these associated services are to be dereferenced.
          </para>
         </section>
      </section>
      <section id="sid-20938800">
         <title>Client Components</title>
         <para>The IOC container, by default, provides a set of default injectable bean types. They range from basic services, to injectable proxies for RPC. This section covers the facilities available out-of-the-box.</para>
         <section id="sid-20938800_ClientComponents-MessageBus">
            <title>MessageBus</title>
            <para>
            The type
            <code>org.jboss.errai.bus.client.framework.MessageBus</code>
            is globally injectable into any bean. Injecting this type will provide the instance of the active message bus running in the client.
          </para>
            <example>
               <title>Injecting a MessageBus</title>
               <programlisting language="java">
@Inject MessageBus bus;
</programlisting>
            </example>
         </section>
         <section id="sid-20938800_ClientComponents-RequestDispatcher">
            <title>RequestDispatcher</title>
            <para>
            The type
            <code>org.jboss.errai.bus.client.framework.RequestDispatcher</code>
            is globally injectable into any bean. Injecting this type will provide a
            <code>RequestDispatcher</code>
            instance capable of delivering any messages provided to it, to the the
            <code>MessageBus</code>
            .
          </para>
            <example>
               <title>Injecting a RequestDispatcher</title>
               <programlisting language="java">
@Inject RequestDispatcher dispatcher;
</programlisting>
            </example>
         </section>
         <section id="sid-20938800_ClientComponents-Caller%3C%3F%3E">
            <title>Caller&lt;?&gt;</title>
            <para>
            The type
            <code>org.jboss.errai.ioc.client.api.Caller&lt;?&gt;</code>
            is a globally injectable RPC proxy. RPC proxies may be provided by various components. For example, JAX-RS or Errai RPC. The proxy itself is agnostic to the underlying RPC mechanism and is qualified by it's type parameterization.
          </para>
            <para>For example:</para>
            <example>
               <title>An example Caller&lt;?&gt; proxy</title>
               <programlisting language="java">
public void MyClientBean {
  @Inject
  private Caller&lt;MyRpcInterface&gt; rpcCaller;
 
  // ... ///
  
  @UiHandler("button")
  public void onButtonClick(ClickHandler handler) { 
    rpcCaller.call(new RemoteCallback&lt;Void&gt;() {
      public void callback(Void void) {
      }
    ).callSomeMethod();
  }
}
</programlisting>
            </example>
            <para>
            The above code shows the injection of a proxy for the RPC remote interface,
            <code>MyRpcInterface</code>
            . For more information on defining RPC proxies see
            <xref linkend="sid-5931313"/>
            and Creating Requests in Errai JAX-RS.
          </para>
         </section>
      </section>
      <section id="sid-21758082">
         <title>Lifecycle Tools</title>
         <para>A problem commonly associated with building large applications in the browser is ensuring that things happen in the proper order when code starts executing. Errai IOC provides you tools which permit you to ensure things happen before initialization, and forcing things to happen after initialization of all of the Errai services.</para>
         <section id="sid-21758082_LifecycleTools-ControllingStartup">
            <title>Controlling Startup</title>
            <para>
            In order to prevent initialization of the the bus and it's services so that you can do necessary configuration, especially if you are writing extensions to the Errai framework itself, you can create an implicit startup dependency on your bean by injecting an
            <code>org.jboss.errai.ioc.client.api.InitBallot&lt;?&gt;</code>
            .
          </para>
            <example>
               <title>Using an InitBallot to Control Startup</title>
               <programlisting language="java">
@Singleton
public class MyClientBean {
  @Inject InitBallot&lt;MyClientBean&gt; ballot;

  @PostConstruct
  public void doStuff() {
    // ... do some work ...
    
    ballot.voteForInit();
  }
}
</programlisting>
            </example>
         </section>
         <section id="sid-21758082_LifecycleTools-PerformingTasksAfterInitialization">
            <title>Performing Tasks After Initialization</title>
            <para>
            Sending RPC calls to the server from inside constructors and
            <code>@PostConstruct</code>
            methods in Errai is not always reliable due to the fact that the bus and RPC proxies initialize asynchronously with the rest of the application. Therefore it is often desirable to have such things happen in a post-initialization task, which is exposed in the
            <code>ClientMessageBus</code>
            API. However, it is much cleaner to use the
            <code>@AfterInitialization</code>
            annotation on one of your bean methods.
          </para>
            <example>
               <title>Using @AfterInitialization to do something after startup</title>
               <programlisting language="java">
@Singleton
public class MyClientBean {
  @AfterInitialization
  public void doStuffAfterInit() {
    // ... do some work ...
  }
}

</programlisting>
            </example>
         </section>
      </section>
   </section>
   <section id="sid-21627016">
      <title>Client-Side Bean Manager</title>
      <para>
        It may be necessary at times to obtain instances of beans managed by Errai IOC from outside the container managed scope or creating a hard dependency from your bean.  Errai IOC provides a simple client-side bean manager for handling these scenarios:
        <code>org.jboss.errai.ioc.client.container.IOCBeanManager</code>
        .
      </para>
      <para>As you might expect, you can inject the bean manager into any of your managed beans.</para>
      <example>
         <title>Injecting the client-side bean manager</title>
         <programlisting language="java">
public MyManagedBean {
  @Inject IOCBeanManager manager;
   
  // class body 
}
</programlisting>
      </example>
      <para>
        If you need to access the bean manager outside a managed bean, such as in a unit test, you can access it by calling
        <code>org.jboss.errai.ioc.client.container.IOC.getBeanManager()</code>
      </para>
      <section id="sid-21627016_Client-SideBeanManager-Lookingupbeans">
         <title>Looking up beans</title>
         <para>
          Looking up beans can be done through the use of the
          <code>lookupBean()</code>
          method in
          <code>IOCBeanManager</code>
          . Here's a basic example:
        </para>
         <example>
            <title>Example lookup of a bean</title>
            <programlisting language="java">
public MyManagedBean {
  @Inject IOCBeanManager manager;
   
  public void lookupBean() {
    IOCBean&lt;SimpleBean&gt; bean = manager.lookupBean(SimpleBean.class);

    // check to see if the bean exists 
    if (bean != null) {
      // get the instance of the bean
      SimpleBean inst = bean.getInstance();
    }
  }
}
</programlisting>
         </example>
         <para>
          In this example we lookup a bean class named
          <code>SimpleBean</code>
          . This example will succeed assuming that
          <code>SimpleBean</code>
          is unambiguous. If the bean is ambiguous and requires qualification, you can do a qualified lookup like so:
        </para>
         <example>
            <title>Looking up beans with qualifiers</title>
            <programlisting language="java">
MyQualifier qual = new MyQualifier() {
  public annotationType() {
    return MyQualifier.class;
  }
}

MyOtherQualifier qual2 = new MyOtherQualifier() {
  public annotationType() {
    return MyOtherQualifier.class;
  }
}

// pass qualifiers to IOCBeanManager.lookupBean
IOCBean&lt;SimpleInterface&gt; bean = beanManager.lookupBean(SimpleBean.class, qual, qual2);
</programlisting>
         </example>
         <para>In this example we manually construct instances of qualifier annotations in order to pass it to the bean manager for lookup. This is a necessary step since there's currently no support for annotation literals in Errai client code.</para>
         <para id="sid-21627016_Client-SideBeanManager-AvailabilityOfBeans"/>
      </section>
      <section id="sid-21627016_Client-SideBeanManager-Availabilityofbeans">
         <title>Availability of beans</title>
         <para>
          Not all beans that are available for injection are available for lookup from the bean manager by default. Only beans which are
          <emphasis role="italics">explicitly</emphasis>
          scoped are available for dynamic lookup. This is an intentional feature to keep the size of the generated code down in the browser.
        </para>
      </section>
   </section>
   <section id="sid-22872133">
      <title>Alternatives and Mocks</title>
      <section id="sid-22872133_AlternativesandMocks-Alternatives">
         <title>Alternatives</title>
         <para>It may be desirable to have multiple matching dependencies for a given injection point with the ability to specify which implementation to use at runtime. For instance, you may have different versions of your application which target different browsers or capabilities of the browser. Using alternatives allows you to share common interfaces among your beans, while still using dependency injection, by exporting consideration of what implementation to use to the container's configuration.</para>
         <para>Consider the following example:</para>
         <informalexample>
            <programlisting language="java">
@Singleton @Alternative
public class MobileView implements View {
  // ... //
}
</programlisting>
         </informalexample>
         <para>and</para>
         <informalexample>
            <programlisting language="java">
@Singleton @Alternative
public class DesktopView implements View {
  // ... // 
</programlisting>
         </informalexample>
         <para>
          In our controller logic we in turn inject the
          <code>View</code>
          interface:
        </para>
         <informalexample>
            <programlisting language="java">
@EntryPoint
public class MyApp {
  @Inject
  View view;
  
  // ... //
}
</programlisting>
         </informalexample>
         <para>
          This code is unaware of the implementation of
          <code>View</code>
          , which maintains good separation of concerns. However, this of course creates an ambiguous dependency on the
          <code>View</code>
          interface as it has two matching subtypes in this case. Thus, we must configure the container to specify which alternative to use. Also note, that the beans in both cases have been annotated with
          <code>javax.enterprise.inject.Alternative</code>
          .
        </para>
         <para>
          In your
          <code>ErraiApp.properties</code>
          for the module, you can simply specify which active alternative should be used:
        </para>
         <informalexample>
            <programlisting language="java">
errai.ioc.enabled.alternatives=org.foo.MobileView
</programlisting>
         </informalexample>
         <para>You can specify multiple alternative classes by white space separating them:</para>
         <informalexample>
            <programlisting language="ini">
errai.ioc.enabled.alternatives=org.foo.MobileView \
                               org.foo.HTML5Orientation \
                               org.foo.MobileStorage 
</programlisting>
         </informalexample>
         <para>You can only have one enabled alternative for a matching set of alternatives, otherwise you will get ambiguous resolution errors from the container.</para>
      </section>
      <section id="sid-22872133_AlternativesandMocks-TestMocks">
         <title>Test Mocks</title>
         <para>
          Similar to alternatives, but specifically designed for testing scenarios, you can replace beans with mocks at runtime for the purposes of running unit tests. This is accomplished simply by annotating a bean with the
          <code>org.jboss.errai.ioc.client.api.TestMock</code>
          annotation. Doing so will prioritize consideration of the bean over any other matching beans while running unit tests.
        </para>
         <para>Consider the following:</para>
         <informalexample>
            <programlisting language="java">
@ApplicationScoped
public class UserManagementImpl implements UserManagement {
  public List&lt;User&gt; listUsers() {
     // do user listy things!
  } 
}
</programlisting>
         </informalexample>
         <para>
          You can specify a mock implementation of this class by implementing its common parent type (
          <code>UserManagement</code>
          ) and annotating that class with the
          <code>@TestMock</code>
          annotation inside your test package like so:
        </para>
         <informalexample>
            <programlisting language="java">
@TestMock @ApplicationScoped
public class MockUserManagementImpl implements UserManagement {
  public List&lt;User&gt; listUsers() { 
     // return only a test user.
     return Collections.singletonList(TestUser.INSTANCE);
  }
}
</programlisting>
         </informalexample>
         <para>
          In this case, the container will replace the
          <code>UserManagementImpl</code>
          with the
          <code>MockUserManagementImpl</code>
          automatically when running the unit tests.
        </para>
         <para>
          The
          <code>@TestMock</code>
          annotation can also be used to specify alternative providers during test execution. For example, it can be used to mock a
          <code>Caller&lt;T&gt;</code>
          .
          <code>Callers</code>
          are used to invoke RPC or JAX-RS endpoints. During tests you might want to replace theses callers with mock implementations. For details on providers see
          <xref linkend="sid-5931407"/>
          .
        </para>
         <informalexample>
            <programlisting language="java">
@TestMock @IOCProvider
public class MockedHappyServiceCallerProvider implements ContextualTypeProvider&lt;Caller&lt;HappyService&gt;&gt; {
 
  @Override
  public Caller&lt;HappyService&gt; provide(Class&lt;?&gt;[] typeargs, Annotation[] qualifiers) {
    return new Caller&lt;HappyService&gt;() {
      ...
    }
}
</programlisting>
         </informalexample>
      </section>
   </section>
   <section id="sid-22872238">
      <title>Bean Lifecycle</title>
      <para>
        All beans managed by the Errai IOC container support the
        <code>@PostConstruct</code>
        and
        <code>@PreDestroy</code>
        annotations.
      </para>
      <para>
        Beans which have methods annotated with
        <code>@PostConstruct</code>
        are guaranteed to have those methods called before the bean is put into service, and only after all dependencies within its graph has been satisfied.
      </para>
      <para>
        Beans are also guaranteed to have their
        <code>@PreDestroy</code>
        annotated methods called before they are destroyed by the bean manager.
      </para>
      <important>
         <para>This cannot be guaranteed when the browser DOM is destroyed prematurely due to: closing the browser window; closing a tab; refreshing the page, etc.</para>
      </important>
      <section id="sid-22872238_BeanLifecycle-DestructionofBeans">
         <title>Destruction of Beans</title>
         <para>
          Beans under management of Errai IOC, of any scope, can be explicitly destroyed through the client bean manager. Destruction of a managed bean is accomplished by passing a reference to the
          <code>destroyBean()</code>
          method of the bean manager.
        </para>
         <example>
            <title>Destruction of bean</title>
            <programlisting language="java">
public MyManagedBean {
  @Inject IOCBeanManager manager;

  public void createABeanThenDestroyIt() {
    // get a new bean.
    SimpleBean bean = manager.lookupBean(SimpleBean.class).getInstance();

    bean.sendMessage("Sorry, I need to dispose of you now");

    // destroy the bean!
    manager.destroyBean(bean);
  }
}
</programlisting>
         </example>
         <para>When the bean manager "destroys" the bean, any pre-destroy methods the bean declares are called, it is taken out of service and no longer tracked by the bean manager. If there are references on the bean by other objects, the bean will continue to be accessible to those objects.</para>
         <important>
            <para>Container managed resources that are dependent on the bean such as bus service endpoints or CDI event observers will also be automatically destroyed when the bean is destroyed.</para>
         </important>
         <para>Another important consideration is the rule, "all beans created together are destroyed together." Consider the following example:</para>
         <example>
            <title>SimpleBean.class</title>
            <programlisting language="java">
@Dependent
public class SimpleBean {
   @Inject @New AnotherBean anotherBean;

   public AnotherBean getAnotherBean() {
     return anotherBean;
   }

   @PreDestroy
   private void cleanUp() {
     // do some cleanup tasks
   }
}
</programlisting>
         </example>
         <example>
            <title>Destroying bean from subgraph</title>
            <programlisting language="java">
public MyManagedBean {
  @Inject IOCBeanManager manager;

  public void createABeanThenDestroyIt() {
    // get a new bean.
    SimpleBean bean = manager.lookupBean(SimpleBean.class).getInstance();

    // destroy the AnotherBean reference from inside the bean
    manager.destroyBean(bean.getAnotherBean());
  }
}
</programlisting>
         </example>
         <para>
          In this example we pass the instance of
          <code>AnotherBean,</code>
          created as a dependency of
          <code>SimpleBean,</code>
          to the bean manager for destruction. Because this bean was created at the same time as its parent, its destruction will also result in the destruction of
          <code>SimpleBean</code>
          ; thus, this action will result in the
          <code>@PreDestroy</code>
            <code>cleanUp()</code>
          method of
          <code>SimpleBean</code>
          being invoked.
        </para>
         <section id="sid-22872238_BeanLifecycle-Disposers">
            <title>Disposers</title>
            <para>
            Another way which beans can be destroyed is through the use of the injectable
            <code>org.jboss.errai.ioc.client.api.Disposer&lt;T&gt;</code>
            class. The class provides a straight forward way of disposing of bean type.
          </para>
            <para>For instance:</para>
            <example>
               <title>Destroying bean with disposer</title>
               <programlisting language="java">
public MyManagedBean {
  @Inject @New SimpleBean myNewSimpleBean;
  @Inject Disposer&lt;SimpleBean&gt; simpleBeanDisposer;

  public void destroyMyBean() {
    simpleBeanDisposer.dispose(myNewSimpleBean);
  }
}
</programlisting>
            </example>
         </section>
      </section>
   </section>
</chapter>
