Java Dynamic Management Kit 5.1 Tutorial

3.4 Creating a Model MBean

To ensure coherence in an agent application, you should define the target object of an MBean before you expose it for management. This implies that you should call the setManagedResource method before registering the model MBean in the MBean server.

Example 3–4 shows how our application creates the model MBean. First it calls the subroutine given in Example 3–1 to build the descriptors and management interface of the model MBean. Then it instantiates the required model MBean class with this metadata. Finally, it creates and sets the managed resource object before registering the model MBean.


Example 3–4 Setting the Default Target Object

ObjectName mbeanObjectName = null;
String domain = server.getDefaultDomain();
String mbeanName = "ModelSample";

try
{
     mbeanObjectName = new ObjectName(
                               domain + ":type=" + mbeanName);
} catch (MalformedObjectNameException e) {
     e.printStackTrace();
     System.exit(1);
}
[...]

// Create the descriptors and ModelMBean*Info objects
// of the management interface
//
buildDynamicMBeanInfo( mbeanObjectName, mbeanName );

try {
    RequiredModelMBean modelmbean =
        new RequiredModelMBean( dMBeanInfo );
    // Set the managed resource for the ModelMBean instance
    modelmbean.setManagedResource( new TestBean(), "objectReference");

    // register the model MBean in the MBean server
    server.registerMBean( modelmbean, mbeanObjectName );

} catch (Exception e) {
     echo("\t!!! ModelAgent: Could not create the " + mbeanName +
                 " MBean !!!");
     e.printStackTrace();
     System.exit(1);
}

The model MBean is now available for management operations and remote requests, just like any other registered MBean.