所有兼容的 MBeanServer 将通知 MBean 注册和注销事件的侦听器。关键是在 MBeanServerDelegate 上注册一个通知监听器。
例如,一个javax.management.NotificationListener实现:
public class MBeanEventListener implements NotificationListener {
public void handleNotification(Notification notification, Object handback) {
MBeanServerNotification mbs = (MBeanServerNotification) notification;
if(MBeanServerNotification.REGISTRATION_NOTIFICATION.equals(mbs.getType())) {
log("MBean Registered [" + mbs.getMBeanName() + "]");
} else if(MBeanServerNotification.UNREGISTRATION_NOTIFICATION.equals(mbs.getType())) {
log("MBean Unregistered [" + mbs.getMBeanName() + "]");
}
}
}
要注册侦听器,请针对MBeanServerDelegate添加通知侦听器。如果您想过滤您实际收到通知的 MBean,则可以使用MBeanServerNotificationFilter 。在此示例中,为所有 ObjectName 启用了过滤器。
// Get a reference to the target MBeanServer
MBeanServerConnection server = ManagementFactory.getPlatformMBeanServer();
MBeanServerNotificationFilter filter = new MBeanServerNotificationFilter();
filter.enableAllObjectNames();
server.addNotificationListener(MBeanServerDelegate.DELEGATE_NAME, new MBeanEventListener(), filter, null);
每次注册或取消注册 MBean 时,您的侦听器实现都会收到回调。