假设我们有一个叫MainConfig 的配置类要需要经常进行改动,那么我们就把它写成一个MBean。
1、 MainConfig MBean接口
在写MBean之前,我们先需要写一个MBean接口,接口里的方法都是属性的set/get方法。
public interface MainConfigMBean { public String getUserName(); public void setUserName(String userName); public String getSex(); public void setSex(String sex); public int getAge(); public void setAge(int age); public void goCall(); // 测试方法,后面提到 }
2、 MainConfig 实现类
然后写出 MainConfigMBean 接口的实现类 MainConfig , 这种类再简单不过了,就是属性和相应的set/get方法。
public class MainConfig implements MainConfigMBean { private String userName = "zhangsan"; private String sex = "1"; private int age = 22; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public void goCall(){ new TestMainConfig().go(); } }
3、为了测试,我们编写测试类:
public class TestMainConfig { public void go(){ MainConfigMBean mainConfigMBean = (MainConfigMBean)MBeanProxyExt.create(MainConfigMBean.class, ObjectNameFactory.create("127.0.0.1:service=MainConfig")); System.out.println(mainConfigMBean.getUserName()); System.out.println(mainConfigMBean.getSex()); System.out.println(mainConfigMBean.getAge()); } }
4、接下来是配置文件。放到META-INF下jboss-service.xml :
<?xml version="1.0" encoding="UTF-8"?> <server> <mbean code="com.mouer.mbean.MainConfig" name="127.0.0.1:service=MainConfig"> <attribute name="UserName"></attribute> <attribute name="Age"></attribute> <attribute name="Sex"></attribute> </mbean> </server>
5、ant构建脚本,可选。主要是打成sar 包
<?xml version="1.0" encoding="UTF-8"?> <project name="Packaging Generator" default="_packaging_generation_"> <target name="_packaging_generation_" depends="SAR" /> <target name="SAR" description="WDPF.sar"> <jar destfile="WDPF.sar"> <zipfileset dir="classes/META-INF" prefix="META-INF"> <include name="jboss-service.xml" /> </zipfileset> <zipfileset dir="classes" includes="**/*.class" /> </jar> </target> </project>
6、部署sar包,然后看其效果。
![](http://dl.iteye.com/upload/attachment/407764/d10ceb03-330c-3ec7-b84b-8af3fe59d79d.bmp)
![](http://dl.iteye.com/upload/attachment/407766/3ee9df1f-c493-3365-b354-10890f5a0cbb.bmp)
7.、测试修改: 我先点goCall()测试下,再把名字改成mouer测试下:如图
![](http://dl.iteye.com/upload/attachment/407762/8cf8bb7e-1c15-3728-8fbb-98126155358e.bmp)
![](http://dl.iteye.com/upload/attachment/407762/8cf8bb7e-1c15-3728-8fbb-98126155358e.bmp)