All configuration classes derived from
AbstractConfiguration
allow to register event listeners, which
are notified whenever the configuration's data is changed. This provides
an easy means for tracking updates on a configuration.
Objects that are interested in update events triggered by configurations
must implement the
ConfigurationListener
interface. This interface defines a
single method configurationChanged()
, which is passed a
ConfigurationEvent
object. The event object contains all
information available about the modification, including:
For resolving the numeric event type use constants defined in
AbstractConfiguration
or derived classes. These constants
start with the prefix EVENT_
and have a speaking name. Here
is an incomplete list of available event types with the configuration
classes, in which they are defined:
addNodes()
method was called),
EVENT_CLEAR_TREE (the clearTree()
method was called)Implementing an event listener is quite easy. As an example we are going to define an event listener, which logs all received configuration events to the console. The class could look as follows:
import org.apache.commons.configuration.event.ConfigurationEvent; import org.apache.commons.configuration.event.ConfigurationListener; public class ConfigurationLogListener implements ConfigurationListener { public void configurationChanged(ConfigurationEvent event) { if (!event.isBeforeUpdate()) { // only display events after the modification was done System.out.println("Received event!"); System.out.println("Type = " + event.getType()); if (event.getPropertyName() != null) { System.out.println("Property name = " + event.getPropertyName()); } if (event.getPropertyValue() != null) { System.out.println("Property value = " + event.getPropertyValue()); } } } }
Now an instance of this event listener class has to be registered at a configuration object:
AbstractConfiguration config = ... // somehow create the configuration ConfigurationListener listener = new ConfigurationLogListener(); config.addConfigurationListener(listener); ... config.addProperty("newProperty", "newValue"); // will fire an event