# 20.2.3　代理 MBean

Spring 的 MBeanProxyFactoryBean 是一个代理工厂 bean，像我们在第 15 章中所演示的远程代理工厂 bean 类似。在前面所介绍的内容中，它们会提供代理，用来访问远程的 Spring 受管 bean，与之不同，MBcanProxyFactoryBean 可以让我们可以直接访问远程的 MBean（就如同配置在本地的其他 bean 一样）。图 20.4 展示了它的工 作原理。

![图 20.4 MBeanFactoryBean 创建远程 MBean 的代理。客户端通过此代理与远程 MBean 进行交互，就像它是本地 Bean 一样](/files/-LnzwDlCuJllde4VhnH6)

例如，考虑如下的 MBeanProxyFactoryBean 声明：

```java
@Bean
public MBeanProxyFactoryBean remoteSpittleControllerMBean(
    MBeanServerConnection mbeanServerClient) {
  MBeanProxyFactoryBean proxy = new MBeanProxyFactoryBean();
  proxy.setObjectName("");
  proxy.setServer(mbeanServerClient);
  proxy.setProxyInterface(SpittleControllerManagedOperations.claas);
  return proxy;
}
```

objectName 属性指定了远程 MBean 的对象名称。在这里是引用我们之前导出的 SpittleControllerMBean。

server 属性引用了 MBeanServerConnection，通过它实现 MBean 所有通信的路由。在这里，我们注入了之前配置的 MBeanServerConnectionFactoryBean。

最后，proxyInterface 属性指定了代理需要实现的接口。在本示例中，我们使用 20.1.2 小节所定义的 SpittleControllerManagedOperations 接口。

对于上面声明的 remoteSpittleControllerMBean，我们现在可以把它注入到类型为 SpittleControllerManagedOperations 的 bean 属性中，并使用它来访问远程的 MBean。这样，我们就可以调用 setSpittlesPerPage() 和 getSpittlesPerPage() 方法了。

我们已经看到与 MBean 通信的几种方式，现在我们可以在应用运行的时候显示和调整 Spring bean 配置。但是目前为止，这都是单方面的会话。都是我们与 MBean 在沟通。现在是时候通过监听通知 （notification）来倾听它们在说什么。


---

# 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-2/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.
