link
Avalon
Avalon Central
Home PlanetProductsCentral
Using Merlin
Adding Configuration Support to the Component

To be supplied with a configuration, our component must either declare a Configuration as a constructor argument, or alternatively, implement the Avalon Framework Configurable interface.

The following code is the HelloComponent extended to include a configuration constructor argument and updates to log the source of the configuration based on runtime information.

Resources supporting this tutorial are contained in the tutorials/configuration/injection directory.

public class HelloComponent
{
   /**
    * Configuration of the component by the container.  The 
    * implementation get a child element named 'source' and 
    * assigns the value of the element to a local variable.
    *
    * @param config the component configuration
    * @exception ConfigurationException if a configuration error occurs
    */
    public HelloComponent( 
      final Logger logger, final Configuration config ) 
      throws ConfigurationException
    {
        logger.info( "instantiation" );
        final String source = 
          config.getChild( "source" ).getValue( "unknown" );
        final String message = "source: " + source;
        logger.info( message );
    }
}

The alternative approach to configuration supply is via the Avalon Configurable interface - demonstrated in the following code example.

Reter tutorials/configuration/block.

/**
 * A configurable component.
 *
 * @avalon.component version="1.0" name="simple"
 */
public class HelloComponent extends AbstractLogEnabled 
  implements Configurable, Initializable
{
    private String m_source = "undefined";

   /**
    * Configuration of the component by the container.  The 
    * implementation get a child element named 'source' and 
    * assigns the value of the element to a local variable.
    *
    * @param config the component configuration
    * @exception ConfigurationException if a configuration error occurs
    */
    public void configure( Configuration config ) 
      throws ConfigurationException
    {
        getLogger().info( "configuration stage" );
        m_source = config.getChild( "source" ).getValue( "unknown" );
    }

   /**
    * Initialization of the component by the container.
    * @exception Exception if an initialization error occurs
    */
    public void initialize() throws Exception
    {
        getLogger().info( "initialization stage" );
        final String message = 
          "source: " + m_source;
        getLogger().info( message );
    }
}
Declaring a Configuration

A number of different approaches to controlling the configuration that is supplied to a component are presented in the next tutorial.