# 20.1.4　处理 MBean 冲突

到目前为止，我们已经看到可以使用多种方式在 MBean 服务器中注册 MBean。在所有的示例中，我们为 MBean 指定的对象名称是由管理域名和 key-value 对组成的。如果 MBean 服务器中不存在与我们 MBean 名字相同的已注册的 MBean，那我们的 MBean 注册时就不会有任何问题。但是如果名字冲突时，将会发生什么呢？

默认情况下，MBeanExporter 将抛出 InstanceAlreadyExistsException 异常，该异常表明 MBean 服务器中已经存在相同名字的 MBean。不过，我们可以通过 MBeanExporter 的 registrationBehaviorName 属性或者 \<context:mbean-export> 的 registration 属性指定冲突处理机制来改变默认行为。

Spring 提供了 3 种借助 registrationBehaviorName 属性来处理 MBean 名字冲突的机制：

* FAIL\_ON\_EXISTING：如果已存在相同名字的 MBean，则失败（默认行为）；
* IGNORE\_EXISTING：忽略冲突，同时也不注册新的 MBean；
* REPLACING\_EXISTING：用新的 MBean 覆盖已存在的 MBean；

例如，如果我们使用 MBeanExporter，我们可以通过设置 registrationBehaviorName 属性为 RegistrationPolicy.IGNORE\_EXISTING 来忽略冲突，如下所示：

```java
@Bean
public MBeanExporter mbeanExporter(SpittleControiler spittleControiler, MBeanlnfoAssembler assembler) {
  MBeanExporter exporter = new MBeanExporter();
  Map<String, Object> beans = new HashMap<String, Object>();
  beans.put("spitter:name=SpittleController", spittleController);
  exporter.setBeans(beans);
  exporter.setAssembler(assembler);
  exporter.setRegistrationPolicy(RegistrationPolicy.IGNORE_EXISTING);
  return exporter;
}
```

registrationBehaviorName 属性可以接受 RegistrationPolicy 中所定义的枚举值，每一个取值分别对应 3 种冲突处理机制的一种。

现在我们已使用 MBeanExporter 注册了我们的 MBean，我们还需要一种方式来访问它们并进行管理。正如之前所看到的，我们可以使用诸如 JConsole 之类的工具来访问本地的 MBean 服务器，进而显示和操纵 MBean，但是像 JConsole 之类的工具并不适合在程序中对 MBean 进行管理。我们如何在一个应用中操纵另一个应用中的 MBean 呢？幸运的是，还存在另一种方式可以把 MBean 作为远程对象进行访问。让我们进一步研究 Spring 对远程 MBean 的支持，了解如何通过远程接口以标准的方式来访问 MBean。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://potoyang.gitbook.io/spring-in-action-v4/untitled-13/untitled-3/untitled.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
