# 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_2_0.xsd"
                xmlns="urn:jboss:bean-deployer:2.0">

             <!-- 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_2_0.xsd"
                xmlns="urn:jboss:bean-deployer:2.0">

             <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 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 Micorcontainer invokes:

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

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

## Factories

Not all classes have pubic 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 uses 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);

Sometimes it is still useful to be able to set or inject a value which can be morphed / progressed into the needed type although the existing type is not compatible (normally getting `ClassCastException`). This is mostly true for `java.lang.Number` subclasses. Let's see how `progression` is used in the following example (here we use `<inject />`, which is actually explained in the next chapter).

       <bean name="FromBean" class="org.jboss.test.kernel.config.support.SimpleBean">
          <property name="adouble">123.456</property>
          <property name="AFloat" class="java.lang.Float">987.6543</property>
          <property name="anInt">314159</property>
       </bean>

       <bean name="SimpleBean" class="org.jboss.test.kernel.config.support.SimpleBean">
          <property name="anint">
             <inject bean="FromBean" property="adouble" />
          </property>

          <property name="AShort">
             <inject bean="FromBean" property="AFloat" />
          </property>

          <property name="AFloat">
             <inject bean="FromBean" property="anInt" />
          </property>
       </bean>

SimpleBean is a plain JavaBean, property names reflect the field type: having a`double` property name means that a field is of type double. A`Float` corresponds to Float type. Etc.

You can change the progression behavior by setting the System property `org.jboss.reflect.plugins.progressionConvertor`, putting the ProgressionConvertor's implementation fully qualified class name as value. By default the SimpleProgressionConvertor implementation is used. Another existing implementation is NullProgressionConvertor, which doesn't do any actual progression.

## 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 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

## Value Factory

Similar to using `inject`'s property attribute, we sometimes want to use other beans to create new values from bean's multi parameter methods.

       <bean name="PropHolder"
         class="org.jboss.test.kernel.config.support.PropHolder">
          <property name="value">
             <value-factory bean="ldap" method="getValue">
                <parameter>xyz.key</parameter>
                <parameter>xyz</parameter>
                <parameter>
                   <bean name="t"
                     class="org.jboss.test.kernel.config.support.TrimTransformer"/>
                </parameter>
             </value-factory>
          </property>
       </bean>

       <bean name="ldap" class="org.jboss.test.kernel.config.support.LDAPFactory">
          <constructor>
             <parameter>
                <map keyClass="java.lang.String" valueClass="java.lang.String">

                   <entry>
                      <key>foo.bar.key</key>
                      <value>QWERT</value>
                   </entry>

                   <entry>
                      <key>xyz.key</key>
                      <value>QWERT</value>
                   </entry>

                </map>

             </parameter>
          </constructor>
       </bean>

For the quick usage there is also shorthand version of the value-factory element, having single parameter as string attribute.

       <bean name="PropHolder"
         class="org.jboss.test.kernel.config.support.PropHolder">
          <constructor>
             <parameter>
                <value-factory bean="ldap" method="getValue" parameter="foo.bar.key"/>
             </parameter>
          </constructor>
       </bean>

You can also define a default value for the value-factory return value.

       <bean name="PropHolder"
         class="org.jboss.test.kernel.config.support.PropHolder">
          <property name="list">
             <list elementClass="java.lang.String">
                <value-factory bean="ldap" method="getValue" default="QWERT">
                   <parameter>no.such.key</parameter>
                </value-factory>
             </list>
          <property>
       </bean>

## 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 an `"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">

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

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

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

                <!-- a list inside a list -->
                <value>
                   <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>

When using collections in your bean configuration, this is the order the Microcontainer will use for new instantiation or using an already existing collection instance.

- if the collection's class attribute is defined, a new instance of that class will be instantiated

- if an already instantiated collection exists and is available via getter, this instance will be used - unless you define the preinstantiate attribute on the property to false

- if the collection references some non interface class, we'll try to instantiate a new instance of that class

- default collection instance will be used - Collection and List will use ArrayList, Set uses HashSet and Map will use HashMap

       <bean name="SimpleBean"
         class="org.jboss.test.kernel.config.support.UnmodifiableGetterBean">
          <property name="list" preinstantiate="false">
             <list elementClass="java.lang.String">
                <value>string1</value>
                <value>string2</value>
             </list>
          </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.

- Pre Install: The scoping description has been examined and classloader dependencies determined.

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

They can also be ignored. See the `jboss-beans.xml` with the `ignore` attribute set to true on the start element.

       public class Example
       {
          public void start() {}
       }

       <bean name="Name1" class="com.acme.Example">
          <start ignore="true"/>
       </bean>

In this case the Microcontainer would not invoke the start method when passing over Start state.

## 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="Name3" ...>
          </bean>

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

       </deployment>

## Annotations via XML

With the new Microcontainer 2.0 we've added support for annotations via XML. Meaning you can have annotation support where the annotation is not part of the bean class's bytecode. Each annotation is set per bean instance and you can set annotations on the following types:

- deployment (all beans inherit this annotations)

- bean

- constructor

- lifecycle

- install / uninstall

- callback

- annotated value

Let's see some use cases on the examples below.

       <deployment name="SimpleDeployment" xmlns="urn:jboss:bean-deployer:2.0">

          <annotation>@org.jboss.test.kernel.deployment.xml.support.Annotation1</annotation>
          <annotation>@org.jboss.test.kernel.deployment.xml.support.AnnotationWithAttributes(clazz=java.lang.Integer.class, integer=100, str="Annotations are nice")</annotation>

          <bean name="bn1" class="org.jboss.test.Example1">
             <annotation>@org.jboss.test.kernel.deployment.xml.support.Annotation2</annotation>
             <annotation>@org.jboss.test.kernel.deployment.xml.support.Annotation3</annotation>
          </bean>

          <bean name="bn2" class="org.jboss.test.Example2">
             <constructor>
                <annotation>@org.jboss.test.kernel.deployment.xml.support.Annotation3</annotation>
             </constructor>
          </bean>

          <bean name="bn3" class="org.jboss.test.Example3">
             <install method="someMethod">
                <annotation>@org.jboss.test.kernel.deployment.xml.support.Annotation1</annotation>
             </install>
          </bean>

          <bean name="bn4" class="org.jboss.test.Example4">
             <create>
                <annotation>@org.jboss.test.kernel.deployment.xml.support.Annotation1</annotation>
             </create>
          </bean>

          <bean name="bn5" class="org.jboss.test.Example5">
             <property name="PropertyName">
                <annotation>@org.jboss.test.kernel.deployment.xml.support.Annotation1</annotation>
                <value>123</value>
             </property>
          </bean>

       </deployment>

The only issue with having annotations defined via XML is that they are per instance basis - as already mentioned, not added at compile time. In this case you need an external mechanism in order to do the annotation inspection. In the Microcontainer this is its metadata repository. See how this is done in Reference Manual, TODO.

## Alias

Mostly each bean will have one unique name, but sometimes it is useful to be able to have an extra name. The extra ones are considered aliases.

       <bean xmlns="urn:jboss:bean-deployer:2.0" class="org.acme.Example">
          <alias>SimpleAlias</alias>
       </bean>

As with all String values you can have System property replacement as part of actual alias value. Additionally you can specify if this replacement is ignored. Or you can even convert a final alias String value into any other class supported by PropertyEditors by setting the class attribute on an alias element. Lets see this configuration on the examples below.

       <bean xmlns="urn:jboss:bean-deployer:2.0" class="org.acme.Example">
          <alias>${example.cluster.name}</alias>
       </bean>

       <bean xmlns="urn:jboss:bean-deployer:2.0" class="org.acme.Example">
          <alias replace="false">X${alias.test.name}X</alias>
       </bean>

       <bean xmlns="urn:jboss:bean-deployer:2.0" class="org.acme.Example">
          <alias class="java.lang.Integer">12345</alias>
       </bean>

Having to specify all aliases when the bean is actually defined is not always adequate however. It is sometimes desirable to introduce an alias for a bean which is defined elsewhere. In XML-based configuration metadata this may be accomplished via the use of the standalone `<alias/>` element.

       <deployment name="FirstDeployment" xmlns="urn:jboss:bean-deployer:2.0">

          <bean name="Bean1" class="java.lang.Object"/>

          <bean name="Bean2" class="java.lang.Object"/>

       </deployment>

       <deployment name="SecondDeployment" xmlns="urn:jboss:bean-deployer:2.0">

          <bean name="Xyz1" class="java.lang.Object">
             <property name="locker1"><inject name="Lock1"></property>
             <property name="locker2"><inject name="Lock2"></property>
          </bean>

          <alias name="Bean1">Lock1</alias>

          <alias name="Bean2">Lock2</alias>
       </deployment>

A newly added alias defined as a element on the deployment acts as a full dependency item. Meaning it won't get registered (installed) until the original bean is installed. What this means is that you can have original beans defined in one deployment and aliases in another, and the order of deployment doesn't matter. When the original bean is uninstalled, the alias gets unregistered (uninstalled) as well. When the alias gets unregistered, all beans that depend on the alias get undeployed as well, regardless of if the original bean is still present.

## Supply and Demand

There is another useful definition of loosely coupled dependency. Each bean can define which beans should be installed for it to move to certain state.

       <bean name="TM" class="com.acme.SomeSingleton">
          <property name="host">http://www.jboss.org</property>
       </bean>

       <bean name="SM" class="com.acme.AnotherSingleton">
          <property name="treadSize">10</property>
       </bean>

       <bean name="Name2" class="com.acme.Example">
          <property name="threadPool"><inject bean="pool"/></property>
          <demand state="Start">TM</demand>
          <demand state="Configure">SM</demand>
       </bean>

       // Example class
       public class Example
       {
          public void start()
          {
             SomeSingleton tm = ...; // should be there!
          }

          public void setThreadPool(ThreadPool pool)
          {
             AnotherSingleton config = ...; // should be there
             pool.setThreadSize(config.getThreadSize());
          }

       }

On the other hand each bean can also provide additional information what it supplies, apart from it self. The actual supply doesn't need to be bound to the Microcontainer in any way. More about this feature with the actual example.

       public class FooBarBinder extends JndiBinder
       {
          public void start()
          {
             FooBar foobar = new FooBar();
             bindToJndi("fbName", foobar);
          }

       }

       public class FooBarConsumer
       {
          public FooBarConsumer()
          {
             FooBar foobar = ...; // get it from jndi. should be there
          }
       }

       <bean name="provider" class="com.acme.FooBarBinder">
          <supply>foobar</supply>
       </bean>

       <bean name="consumer" class="com.acme.FooBarConsumer">
          <demand state="Instantiate">foobar</demand>
       </bean>

## Contextual Awareness

With existing annoyance of using huge amounts of xml to sometimes wire up trivial beans, IoC containers provide a simpler solution called autowiring. Beans, specially singletons, can often be wired with a simple class type knowledge. But with huge systems you should use this feature with care, since it can easly get broken with addition of another bean that would satisfy contextual dependency. The existing 2.0.0 version supports three ways of autowiring:

- full bean autowiring

- property / parameter injection

- callback injection

On the other hand, if you don't want a particular bean to be involved as a candidate for autowiring, you can set the bean element's attribute `autowire-candidate` to false.

       <bean name="ignored" class="com.acme.Example" autowire-candidate="false" />

TODO for bean autowiring.

       <bean name="autowired" class="com.acme.Example" autowire="true" />

When doing a propery / parameter injection of some existing bean, you can omit the bean attibute, meaning that the Microcontainer will do the injection based on the information from the property / parameter class type. If no such information is available, an exception will be thrown. If no such bean is eventually available, you can define the behavior after validation. For Strict option the deployment will fail, for Callback see the callback injection below. There is also a way of doing contextual injection based on property name. Property name will be matched against newly wired bean's name.

       <bean name="pool" class="com.acme.ThreadPoolImpl"/>

       <bean name="propInj" class="com.acme.Example">
          <property name="threadPool"><inject/></property>
       </bean>

       <bean name="paramInj" class="com.acme.Example">
          <constructor>
             <parameter name="threadPool"><inject/></parameter>
          </constructor>
       </bean>

       public class Example
       {
          protected ThreadPool pool;

          public Example() {}

          public Example(ThreadPool pool)
          {
             this.pool = pool;
          }

          public void setThreadPool(ThreadPool pool)
          {
             this.pool = pool;
          }

       }

Sometimes it is useful to be notified of certain beans being installed / uninstalled by inspecting their class type. In the Microcontainer we call this callbacks. You can define which methods should be used for callback resolution on a particular bean. Usually the method name is sufficient. In the case of having multiple methods with the same name, you can narrow down the exact method by specifying the class type to use for contextual lookup.

       <bean name="editorHolder" class="com.acme.Example">
          <incallback method="addEditor" />
          <uncallback method="removeEditor" />
       </bean>

       <bean name="fbEditor" class="com.acme.FooEditor"/>

       public class Example
       {
          protected Set<Editor> editors = new HashSet<Editor>();

          public Example() {}

          public void addEditor(Editor editor)
          {
             editors.add(editor);
          }

          public void removeEditor(Editor editor)
          {
             editors.remove(editor);
          }
       }

We can do the same callback injection on a property. And there is also an interesting feature available, though it will probably rarely be used. You can define a Cardinality as a condition when that actual dependency is satisfied and injection can take place. The following examples shows how we need at least 2 Editor instances to satisfy callback dependency.

       <bean name="editorHolder" class="com.acme.Example">
          <incallback property="editors" cardinality="2..n" />
          <uncallback property="editors" />
       </bean>

       <bean name="fbEditor" class="com.acme.FooEditor"/>

       <bean name="xyzEditor" class="com.acme.XYZEditor"/>

       public class Example
       {
          protected Set<Editor> editors;

          public Example() {}

          public void setEditors(Set<Editor> editors)
          {
             this.editors = editors;
          }
       }

While using callbacks on the Collection subclasses, currently only basic Collection subinterfaces are supported: List, Set and Queue. See BasicCollectionCallbackItemFactory for more details. But you can change the Collection callback behaviour by providing your own CollectionCallbackItemFactory. You do this by setting the System Property `org.jboss.dependency.collectionCallbackItemFactory` and putting the CollectionCallbackItemFactory implementation fully qualified class name as a value.

## Injection from Context

Even though the Microcontainer is aimed at POJOs, it doesn't mean you are not able to easily get into the underlying architecture of its state machine. Each bean is represented in the Microcontainer's state machine (Controller) as a ControllerContext. The ControllerContext holds various information in order to consistently move between lifecycle states, resolve dependencies, apply instance aspects, annotations, metadata ...

With the already known injection concept (`<inject />`), you can also inject some information from the context. This is what you can currently get a hold on from the underlying context:

- name - `<inject fromContext="name"/>`

- aliases - `<inject fromContext="aliases"/>`

- metadata - `<inject fromContext="metadata"/>`

- beaninfo - `<inject fromContext="beaninfo"/>`

- scope - `<inject fromContext="scope"/>`

- id - `<inject fromContext="id"/>`

- context itself - `<inject fromContext="context"/>`

All this information is wrapped into unmodifiable objects, preventing the user to add or set additional information outside the Microcontainer's Controller. As we already know, the `<inject/>` element can take a `bean` attribute. In this case, if the bean attribute is set, we are not obtaining the target bean's underlying context, but the context that coresponds to the bean being injected.

       <bean name="sndBean"
         class="org.jboss.test.kernel.deployment.support.NameAwareBean">
          <property
    	    name="beaninfo"><inject bean="otherBean" fromContext="beaninfo"/></property>
       </bean>

In this example we inject otherBean's beaninfo information into sndBean bean.