MBean嗅骄,managed bean,被管理的bean韧衣,也就是一個被管理的Java對象极颓。
它暴露了一個管理接口朱盐,可以包含以下內(nèi)容:
- 一系列可讀或可寫的屬性
- 一系列可調(diào)用的操作
- 自我描述
SpringApplicationAdminMXBean
Springboot里默認有暴露出SpringApplicationAdminMXBean,通過源碼可以看出菠隆,是在afterPropertiesSet方法注冊了mbean兵琳,destroy方法取消注冊
@Override
public void afterPropertiesSet() throws Exception {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
server.registerMBean(new SpringApplicationAdmin(), this.objectName);
if (logger.isDebugEnabled()) {
logger.debug("Application Admin MBean registered with name '" + this.objectName + "'");
}
}
@Override
public void destroy() throws Exception {
ManagementFactory.getPlatformMBeanServer().unregisterMBean(this.objectName);
}
該bean本身暴露了兩個屬性(Ready, EmbeddedWebApplication),兩個方法(getProperty, shutdown)
private class SpringApplicationAdmin implements SpringApplicationAdminMXBean {
@Override
public boolean isReady() {
return SpringApplicationAdminMXBeanRegistrar.this.ready;
}
@Override
public boolean isEmbeddedWebApplication() {
return SpringApplicationAdminMXBeanRegistrar.this.embeddedWebApplication;
}
@Override
public String getProperty(String key) {
return SpringApplicationAdminMXBeanRegistrar.this.environment.getProperty(key);
}
@Override
public void shutdown() {
logger.info("Application shutdown requested.");
SpringApplicationAdminMXBeanRegistrar.this.applicationContext.close();
}
}
通過jvisualvm骇径,可以看到具體mbean的信息
自己實現(xiàn)
我們自己也可以仿照Admin類躯肌,自己實現(xiàn)一個MBean
代碼如下,定義了一個MBean: cn.ye:type=Hello
public interface HelloMBean {
public void sayHello();
public int add(int x, int y);
public String getName();
public int getCacheSize();
public void setCacheSize(int size);
}
public class Hello implements HelloMBean {
private final String name = "Reginald";
private int cacheSize = DEFAULT_CACHE_SIZE;
private static final int DEFAULT_CACHE_SIZE = 200;
@Override
public void sayHello() {
System.out.println("hello, world");
}
@Override
public int add(int x, int y) {
return x + y;
}
@Override
public String getName() {
return this.name;
}
@Override
public int getCacheSize() {
return this.cacheSize;
}
@Override
public synchronized void setCacheSize(int size) {
this.cacheSize = size;
System.out.println("Cache size now " + this.cacheSize);
}
}
啟動類里破衔,注冊MBean
public class Application {
public static void main(String[] args) throws MalformedObjectNameException, NotCompliantMBeanException, InstanceAlreadyExistsException, MBeanRegistrationException {
SpringApplication.run(Application.class, args);
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName name = new ObjectName("cn.ye:type=Hello");
Hello mbean = new Hello();
mbs.registerMBean(mbean, name);
}
}
啟動jvisualvm清女,可以發(fā)現(xiàn)mbean已經(jīng)注冊上去了
其中CacheSize可修改,Name只讀
操作里运敢,也有兩個方法校仑,可以正常調(diào)用