package cn.reghao.tnb.sb.config;

import cn.reghao.tnb.sb.config.jmx.SystemInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.management.*;
import java.lang.management.ManagementFactory;

/**
 * @author reghao
 * @date 2022-03-23 09:22:01
 */
@Slf4j
@Component
public class SpringLifecycle implements ApplicationRunner, DisposableBean {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("springboot started...");
        registerJmxMBean();
    }

    private void registerJmxMBean() throws NotCompliantMBeanException, InstanceAlreadyExistsException, MBeanRegistrationException, MalformedObjectNameException {
        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();

        // ObjectName 的规范是: 包名:type=接口名,name=MBean名
        String name = "cn.reghao.tnb.sb.config.jmx:type=SystemInfoMBean,name=systemInfo";
        ObjectName objectName = new ObjectName(name);
        SystemInfo systemInfo = new SystemInfo();
        mBeanServer.registerMBean(systemInfo, objectName);
    }

    @Override
    public void destroy() {
        log.info("springboot shutdown...");
    }
}
