# Basic Configuration and Usage

The microcontainer's main purpose is to allow external configuration of POJOs. As we have seen in examples, the POJOs in a microcontainer applications are nothing special. The key element that drives the application is the `jboss-beans.xml` configuration file. So, in this chapter, we will look at the some of the common configurations in `jboss-beans.xml`.

## Deployment

The `deployment` element acts as a container for many beans that are deployed together.

    <?xml version="1.0" encoding="UTF-8"?>

    <!-- Deployment holds beans -->
    <deployment xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xsi:schemaLocation="urn:jboss:bean-deployer bean-deployer_1_0.xsd"
                xmlns="urn:jboss:bean-deployer">

       <!-- bean part of the deployment -->
       <bean .../>

       <!-- bean part of the deployment -->
       <bean .../>

    </deployment>

## Bean

The `bean` element is the main deployment component. It describes a single managed object in the runtime.

    <deployment xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="urn:jboss:bean-deployer bean-deployer_1_0.xsd"
          xmlns="urn:jboss:bean-deployer">

       <bean name="Simple"
             class="org.jboss.example.microcontainer.simple.SimpleBean"/>

    </deployment>

The example above from the `simple` example uses the default constructor of `SimpleBean` to create a new POJO.

    new org.jboss.example.microcontainer.simple.SimpleBean();

It is given the name `"Simple"` such that it can be referenced elsewhere.

## Construction

The example above uses the default constructor. What if you don't want to use some other constructor. The simplest mechanism just matches the number of parameters in the constructor. The example below is from the `constructor` example.

    public class ConstructorBean
    {
       ... ...

       public ConstructorBean(int integer)
       {
          ... ...
       }

The `jboss-beans.xml` element for creating the POJO using the above constructor is as follows.

    <bean name="Integer"
          class="org.jboss.example.microcontainer.constructor.ConstructorBean">
      <constructor>
        <parameter>4</parameter>
      </constructor>
    </bean>

The microcontainer would just use the following to create the `Integer` named component.

    new ConstructorBean (4);

Sometimes there are two constructors with the same number of parameters. In this case, you must specify the types to resolve the ambiguity.

    public class ConstructorBean {
       public ConstructorBean(String string, int integer) {}
       public ConstructorBean(String string, long long) {}
    }

The following configuration creates a managed bean instance named `StringLong` using the second constructor listed above.

    <bean name="StringLong"
          class="org.jboss.example.microcontainer.constructor.ConstructorBean">
      <constructor>
        <parameter>a string</parameter>
        <parameter class="long">10</parameter>
      </constructor>
    </bean>

Behind the scene, the microcontainer invokes:

    new ConstructorBean (new String("a string"), (long) 10);

Note that you only have to be explicit enough to resolve the ambiguity.

## Factories

Not all classes have public constructors. It is often good practice to use factories when you to have a choice of implementation for an interface. The microcontainer includes support for the several different types of factory. The simplest case is a static factory class with a static factory method like the following from the `factory` example.

    public class StaticFactory
    {
       public static FactoryCreatedBean createBean()
       {
          return new FactoryCreatedBean("StaticFactory.createBean()");
       }
    }

The bean configuration tells the microcontainer to the use the `StaticFactory.createBean()` static method to create an instance of `FactoryCreatedBean`.

    <bean name="StaticFactoryCreatedBean"
        class="org.jboss.example.microcontainer.factory.FactoryCreatedBean">
      <constructor factoryMethod="createBean"
          factoryClass="org.jboss.example.microcontainer.factory.StaticFactory"/>
    </bean>

Of course, the factory class itself does not have to be static. The microcontainer can create a non-static factory itself as a managed object, and then use this factory object to create other bean objects. For instance, the `factory` example contains a singleton factory class example.

    public class SingletonFactory
    {
       private static SingletonFactory singleton;

       public synchronized static SingletonFactory getInstance()
       {
          if (singleton == null)
             singleton = new SingletonFactory();
          return singleton;
       }

       public FactoryCreatedBean createBean()
       {
          return new FactoryCreatedBean("SingletonFactory.createBean()");
       }

       private SingletonFactory()
       {
          System.out.println("SingletonFactory()");
       }
    }

In the following configuration, we first create an instance of the `SingletonFactory` class under the name `"SingletonFactory"` using the `SingletonFactory.getInstance()` static method. Then, we use this factory object to create a `FactoryCreatedBean` instance under the name `SingletonFactoryCreatedBean`.

    <bean name="SingletonFactory"
          class="org.jboss.example.microcontainer.factory.SingletonFactory">
      <constructor factoryMethod="getInstance"
          factoryClass="org.jboss.example.microcontainer.factory.SingletonFactory"/>
    </bean>

    <bean name="SingletonFactoryCreatedBean"
          class="org.jboss.example.microcontainer.factory.FactoryCreatedBean">
      <constructor factoryMethod="createBean">
        <factory bean="SingletonFactory"/>
      </constructor>
    </bean>

Like the constructor method we mentioned before, the factory method can also take call parameters via the nested `parameter` element.

## Properties

It is possible to create all objects using factories and constructors, however many people use the JavaBean or MBean convention where an object is constructed using a default constructor and then configured using properties or attributes (i.e., setter methods). The following class from the `properties` example is a JavaBean style POJO.

    public class PropertiesBean
    {
       public PropertiesBean()
       {
          System.out.println("PropertiesBean()");
       }

       public void setTitle(String title)
       {
          System.out.println("setTitle: " + title);
       }

       public void setSubTitle(String subTitle)
       {
          System.out.println("setSubTitle: " + subTitle);
       }

       public void setLink(URL url)
       {
          System.out.println("setLink: " + url);
       }

       public void setNumber(Number number)
       {
          System.out.println("setNumber: " + number + " type=" + number.getClass().getName());
       }
    }

The configuration creates the `PropertiesBean` instance and then use the setter methods to set its properties.

    <bean name="PropertiesBean"
          class="org.jboss.example.microcontainer.properties.PropertiesBean">
      <property name="title">JBoss Microcontainer property example</property>
      <property name="subTitle"><null/></property>
      <property name="link">http://www.jboss.org</property>
      <property name="number" class="java.lang.Long">4</property>
    </bean>

Here we use the string representation of various objects, including the `null` value. They will be discussed in more detail in the next section.

## String Values

Now, you probably noticed that we use string values to represent all kinds of objects in the `parameter` element for the constructors or factory methods, and in the `property` element for JavaBean properties.

In the most generic case, a JavaBean PropertyEditor can be used to convert a string to a specific type. JBoss already provides a large number of property editors for standard types. Please see the example below for the POJO class, the configuration, and the resultant microcontainer action.

    import java.beans.PropertyEditorSupport;
    public class URLEditor extends PropertyEditorSupport{
       public void setAsText(final String text){
          setValue(new URL(text));
       }
    }

    public class Example{
       public URL getLink() {}
       public void setLink(URL url) {}
    }

    <bean name="Name1" class=com.acme.Example">
       <property name="link">http://acme.com/index.html</property>
    </bean>

    Example example = new com.acme.Example();
    PropertyEditor editor = PropertyEditorManager.findEditor(URL.class);
    editor.setAsText("http://acme.com/index.html");
    example.setLink((URL)editor.getValue());

Often the property takes an interface or abstract class, but you want to pass a specific implementation or a subclass. That is easy. Just specify the implementation class in the `property.class` attribute as show below.

    public class Example{
       public Number getNumber() {}
       public void setNumber(Number number) {}
    }

    <bean name="Name1" class=com.acme.Example">
       <property name="number" class="java.lang.Long">4</property>
    </bean>

    Example example = new com.acme.Example();
    example.setNumber(new Long(4));

There is also a more long-winded form of value that we will see later when configuring collections.

    public class Example{
       public Number getNumber() {}
       public void setNumber(Number number) {}
    }

    <bean name="Name1" class=com.acme.Example">
       <property name="number"><value class="java.lang.Long">4</value></property>
    </bean>

    Example example = new com.acme.Example();
    example.setNumber(new Long(4));

Finally, the `null` value is trivial, <null/>. But, it needs to differentiated from the string "null". Please see the example below for the usage.

    public class Example{
       public String getTitle() {}
       public void setTitle(String string) {}
    }

    <!-- Wrong -->
    <bean name="Name1" class=com.acme.Example">
       <property name="title">null</property>
    </bean>

    Example example = new com.acme.Example();
    example.setTitle(new String("null"));

    <!-- Correct -->
    <bean name="Name1" class="com.acme.Example">
       <property name="title"><null/></property>
    </bean>

    Example example = new com.acme.Example();
    example.setTitle(null);

## Injections

Objects by themself are not very useful. They need to be linked together to form more complicated data structures. We have already seen one form of an injection when using factory instances above. Injections can be used anywhere a string value is used. All the examples that we have previously seen with strings could also be done with injections.

The `injection` example shows how dependency injection works in JBoss Microcontainer. The `InjectionBean` class has a `host` property, which is the `java.net.URL` type. We will inject an URL object into the bean via the microcontainer.

    public class InjectionBean
    {
       String name;

       public InjectionBean(String name)
       {
          this.name = name;
          System.out.println("InjectionBean() " + this);
       }

       public String toString()
       {
          return name;
       }

       public void setHost(String host)
       {
          System.out.println("setHost: " + host + " on " + this);
       }

       public void setOther(InjectionBean other)
       {
          System.out.println("setOther: " + other + " on " + this);
       }
    }

The microcontainer creates the `URL` object first, and then passes the `URL` object as a property into the `InjectionBean1` object when it is instantiated.

    <bean name="URL" class="java.net.URL">
      <constructor>
        <parameter>http://www.jboss.org/index.html</parameter>
      </constructor>
    </bean>

    <bean name="InjectionBean1"
          class="org.jboss.example.microcontainer.injection.InjectionBean">
      <constructor>
        <parameter>InjectionBean1</parameter>
      </constructor>
      <property name="host"><inject bean="URL" property="host"/></property>
    </bean>

The order of the `bean` elements does not matter. The microcontainer orders the beans into the correct order. For instance, in the above example, the `URL` object is always created before the `InjectionBean1` object since the latter is dependent on the former. But that leaves the problem of how to resolve circular dependencies. These can be resolved by specifying when you want the injection to occur. In the example below we say once `Circular1` is "Instantiated" (constructed) it is ok to configure it on `Circular2`. Normally, injections wait for the referenced bean to reach the state "Installed" (see later on life cycles).

    <bean name="Circular1"
          class="org.jboss.example.microcontainer.injection.InjectionBean">
      <constructor>
        <parameter>Circular1</parameter>
      </constructor>
      <property name="other"><inject bean="Circular2"/></property>
    </bean>

    <bean name="Circular2"
          class="org.jboss.example.microcontainer.injection.InjectionBean">
      <constructor>
        <parameter>Circular2</parameter>
      </constructor>
      <property name="other">
        <inject bean="Circular1" state="Instantiated"/>
      </property>
    </bean>

Here is the order the microcontainer instantiates those objects.

    InjectionBean  Circular1 = new InjectionBean ();
    InjectionBean  Circular2 = new InjectionBean ();
    Circular1.setOther(Circular2); // don't wait for a fully configured Circular1
    Circular2.setOther(Circular1); // Complete the confguration of Circular2

## Collections

The `collection`, `list`, `set` and `array` elements are used to enclose collection of values to pass to the bean components as properties or constructor (factory method) parameters. The default types are:

- collection: java.util.ArrayList

- list: java.util.ArrayList

- set: java.util.HashSet

- array: java.lang.Object[]

They all take the same form. So, only `list` is shown here in those examples. You just need to nest `value` elements inside the collection element to specify the contents of the collection. Please note that a `"elementClass"` attribute is required on the collection element, unless you specify explicit types on all the `value`s.

Below is a sample configuration from the `collections` example. It sets a `List` with two elements of mixed types to the `ObjectPrinter.print` property on the `PrintList` named object.

    <bean name="PrintList"
          class="org.jboss.example.microcontainer.collections.ObjectPrinter">
      <constructor><parameter>List</parameter></constructor>
      <property name="print">
        <list elementClass="java.lang.String">
          <value>Value of type elementClass</value>
          <value class="java.lang.Integer">4</value>
        </list>
      </property>
    </bean>

It is also possible to use a `List` as an element inside another `List`. Here is an example.

    <bean name="Name1" class="com.acme.Example">
       <property name="list">
          <list class="java.util.LinkedList" elementClass="java.lang.String">

             <value>A string</value> <!-- uses elementClass -->

             <value class="java.lang.URL">http://acme.com/index.html</value> <!-- a URL -->

             <value><inject bean="SomeBean"/></value> <!-- inject some other bean -->

             <value> <!-- a list inside a list -->
                <list elementClass="java.lang.String">
                   <value>Another string</value>
                </list>
             </value>

          </list>
       </property>
    </bean>

Below is what happens inside the microcontainer.

    Example example = new com.acme.Example();
    List list = new LinkedList();
    list.add(new String("A string"));
    list.add(new URL("http://acme.com/index.html"));
    list.add(someBean);
    List subList = new ArrayList();
    subList.add(new String("Another string"));
    list.add(subList);
    element.setList(list);

The other type of collection is a map which also covers Properties and Hashtables. The default is `java.util.HashMap`. The `entry` element inside the map differentiates each `key` and `value` pair. For maps there are two default types for the elements: the `keyClass` and `valueClass`. Below is a map sample from the `collections` example.

    <bean name="PrintMap"
          class="org.jboss.example.microcontainer.collections.ObjectPrinter">
      <constructor><parameter>Map</parameter></constructor>
      <property name="print">
        <map keyClass="java.lang.String" valueClass="java.lang.String">
          <entry>
            <key>Key1 of type keyClass</key>
            <value>Value1 of type valueClass</value>
          </entry>
          <entry>
            <key>Key2 of type keyClass</key>
            <value class="java.lang.Integer">4</value>
          </entry>
          <entry>
            <key class="java.lang.Long">4</key>
            <value>Value of type valueClass</value>
          </entry>
        </map>
      </property>
    </bean>

## Lifecycle

Anybody familiar with the JBoss JMX microkernel will know about the lifecycle. The microcontainer extends the lifecycle concept to the managed POJOs. A POJO can have the following lifecycle states.

- Not Installed: The POJO has not been described or has been uninstalled.

- Described: The POJO's bean description has been examined and dependencies determined.

- Instantiated: All the dependencies have been resolved to construct the bean, these include, the class exists, the constructor parameter injections can be resolved, any factory can be resolved.

- Configured: All the property injections can be resolved, this includes all the dependencies in any collections.

- Create: All the dependent beans have been "created", this includes any injections passed to the create method.

- Start: All the dependent beans have been "started", this includes any injections passed to the start method.

- Installed: The lifecycle is complete.

- *** ERROR ***: Some unexpected error occured, usually due to misconfiguration.

At each stage of the lifecycle, the corresponding method in the bean class is automatically called by the microcontainer, so that you can programatically control how the objects behave throughout its lifecycle. For instance, the `start()` method in the bean class is called when the bean enters the `Start` state. Below is the `LifecycleBean` class from the `lifecycle` example.

    public class LifecycleBean
    {
       String name;

       public LifecycleBean(String name)
       {
          this.name = name;
          System.out.println("LifecycleBean() " + this);
       }

       public void create()
       {
          System.out.println("create: " + this);
       }

       public void start()
       {
          System.out.println("start: " + this);
       }

       public void stop()
       {
          System.out.println("stop: " + this);
       }

       public void destroy()
       {
          System.out.println("destroy: " + this);
       }

       public String toString()
       {
          return name;
       }
    }

The `depends` element allows two beans to perform two phase startup processing like the JMX microkernel.

    <bean name="Lifecycle1"
          class="org.jboss.example.microcontainer.lifecycle.LifecycleBean">
      <constructor>
        <parameter>Lifecycle1</parameter>
      </constructor>
      <depends>Lifecycle2</depends>
    </bean>

    <bean name="Lifecycle2"
          class="org.jboss.example.microcontainer.lifecycle.LifecycleBean">
      <constructor>
        <parameter>Lifecycle2</parameter>
      </constructor>
    </bean>

The microcontainer resolves the dependency and starts both beans in the appropriate order. Below is the console output when you run the `lifecycle` example. It shows when various lifecycle methods are called when the bean enters those states.

    run:
         [java] LifecycleBean() Lifecycle1
         [java] LifecycleBean() Lifecycle2
         [java] create: Lifecycle2
         [java] create: Lifecycle1
         [java] start: Lifecycle2
         [java] start: Lifecycle1
         [java] stop: Lifecycle1
         [java] stop: Lifecycle2
         [java] destroy: Lifecycle1
         [java] destroy: Lifecycle2

The `create()`, `start()`, `stop()` and `destroy()` methods can be overridden with parameters passed to them. Below is an example on how to override the `create()` method via the `jboss-beans.xml` configuration file.

    public class Example{
       public void initialize(Object someObject) {}
    }

    <bean name="Name1" class="com.acme.Example">
       <create method="initialize">
          <parameter><inject bean="SomeBean"/></parameter>
       </create>
    </bean>

## Installation

As of 2.0.0, you can provide generic install/uninstall actions. Allowing you to dynamically setup repositories. Note the use of `this` to pass yourself as a parameter. If you exlude the bean name on the action, the operation is performed on yourself.

    <bean name="Name1" class="java.util.Timer"/>
    <bean name="Name2" ...>
       <install bean="Name1" method="schedule">
          <parameter><this/></parameter>
          <parameter>100</parameter>
          <parameter>10000</parameter>
       </install>
       <uninstall method="cancel"/>
    </bean>

    // Install
    Name1 = new Timer();
    Name2 = ...;
    Name1.schedule(Name2, 100, 10000);

    // Uninstall
    name2.cancel();

## ClassLoader

The Microcontainer supports configuration of the classloader at either the deployment or bean level. The classloader element has three alternatives.

    // deployment level - applies to all beans in the deployment
    <deployment>
       <classloader><inject bean="ClassLoaderName"/></classloader>

    // bean level
    <bean name="Name2" ...>
       <classloader><inject bean="ClassLoaderName"/></classloader>
    </bean>

    // bean level will use any deployment level classloader
    <bean name="Name2" ...>
    </bean>

    // bean level as null to not use any deployment level classloader
    <bean name="Name2" ...>
       <classloader><null/></classloader>
    </bean>