You need to register each MBean with a unique name. If you do that you will no longer receive the exception when registering the second MBean. You will have to manage each bean separately (i.e. the attribute on each Home object is set through individual MBeans).
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
Hello h1 = new Hello();
Hello h2 = new Hello();
mbs.registerMBean(h1, new ObjectName("mBeans:type=Hello-1"));
mbs.registerMBean(h2, new ObjectName("mBeans:type=Hello-2"));
If you want to manage the two Hello
objects at the same time through one MBean, (i.e change attribute on one MBean results in the change on both Hello objects) you could try using a Composite Hello object and expose that as an MBean.
Common interface:
interface IHello {
void setAttribute(int value);
}
Single hello object:
class Hello implements IHello {
int attribute;
void setAttribute(int value) {
attribute = value;
}
}
Composite hello object:
class CompositeHello implements IHello {
IHello[] Hellos;
CompositeHome(IHello...hellos) {
super();
this.hellos = hellos;
}
void setAttribute(int value) {
for (IHello hello : hello) {
home.setAttribute(value);
}
}
}
Register composite MBean:
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
Hello h1 = new Hello();
Hello h2 = new Hello();
CompositeHello composite = new CompositeHello(h1, h2);
mbs.registerMBean(composite, new ObjectName("mBeans:type=Hello"));